2

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

1 回答 1

2

感谢@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))
于 2018-06-03T12:11:26.773 回答