Need to write a to-string function that accepts integer and string.
(to-string 3) ; -> "3"
(to-string "hello") ; -> "\"hello\""
(to-string "hel\"lo") ; -> "\"hel\\\"lo\""
I managed to do so with:
(define (to-string x)
(define o (open-output-string))
(write x o)
(define str (get-output-string o))
(get-output-bytes o #t)
str
)
(to-string 3)
(to-string "hello")
(to-string "hel\"lo")
However, the get-output-bytes reseting is not very readable. What's the idiomatic Racket way of doing it?
Does the ~v function or the ~s function from racket/format work for you?
> (~v 3)
"3"
> (~v "hello")
"\"hello\""
> (~v "hel\"lo")
"\"hel\\\"lo\""
I'm not sure if ~v and ~s functions still require racket/format library for the #lang racket, but you can use format function (see more details) that works even for the racket/base
#lang racket/base
(format "~v" 3)
(format "~v" "hello")
(format "~v" "hel\"lo")
That gives you exactly what you need:
"3"
"\"hello\""
"\"hel\\\"lo\""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With