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

埃米尔·索内维尔德(Emile Sonneveld)

执行此操作(显示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)}"
埃米尔·索内维尔德(Emile Sonneveld)

通过@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))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章