需要编写一个接受整数和字符串的to-string
函数。
(to-string 3) ; -> "3"
(to-string "hello") ; -> "\"hello\""
(to-string "hel\"lo") ; -> "\"hel\\\"lo\""
我设法这样做:
(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")
然而,get-output-bytes
重置不是非常易读。什么是惯用的球拍方式呢?
答案 0 :(得分:5)
来自racket/format
的~v
功能或~s
功能是否适合您?
> (~v 3)
"3"
> (~v "hello")
"\"hello\""
> (~v "hel\"lo")
"\"hel\\\"lo\""
答案 1 :(得分:2)
我不确定~v
和~s
函数是否还需要racket/format
的{{1}}库,但您可以使用#lang racket
函数(查看更多适用于format
racket/base
这可以满足您的需求:
#lang racket/base
(format "~v" 3)
(format "~v" "hello")
(format "~v" "hel\"lo")