Alojz Janez
Alojz Janez

Reputation: 540

How can I convert code to a string or print it with proper spaces in scheme?

Is there a way to convert code to a string in scheme with proper spaces or even pretty print?

So when I apply this to a form like (+ 1 2) it should result in "(+ 1 2)" and not in "+12".

Upvotes: 3

Views: 530

Answers (2)

Óscar López
Óscar López

Reputation: 236004

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

Upvotes: 7

gcbenison
gcbenison

Reputation: 11963

In guile, you can:

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

Where expr is any value and output-port is any port (such as a string port if you want to capture the output as a string)

Upvotes: 4

Related Questions