3

有没有办法将代码转换为具有适当空格甚至漂亮打印的方案中的字符串?

因此,当我将其应用于 (+ 1 2) 之类的形式时,它应该导致“(+ 1 2)”而不是“+12”。

4

2 回答 2

7

Try quoting the expression, that should be enough for displaying it, and it'll be easier to manipulate (easier than manipulating a string):

(display '(+ 1 2))
=> '(+ 1 2)  ; a quoted expression

Or if you definitely need a string, in Racket you can do something like this - but once again, the expression has to be quoted first:

(format "~a" '(+ 1 2))
=> "(+ 1 2)" ; a string

Yet another way, using a string output port:

(define o (open-output-string))
(write '(+ 1 2) o)
(get-output-string o)
(close-output-port o)
=> "(+ 1 2)" ; a string

Finally, an example using Racket's pretty printing library:

(require racket/pretty)
(define o (open-output-string))
(pretty-write '(+ 1 2) o)
(get-output-string o)
(close-output-port o)
=> "(+ 1 2)\n" ; a formatted string
于 2013-06-08T02:14:38.413 回答
4

在诡计中,您可以:

(use-modules (ice-9 pretty-print))
(pretty-print value output-port)

expr任何值和端口在哪里output-port(例如,如果要将输出捕获为字符串,则为字符串端口)

于 2013-06-08T05:45:52.660 回答