在执行(显示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)}"
答案 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))