"\"hello\"" (to-string "he-6ren">
gpt4 book ai didi

整数和字符串的 Racket 转字符串函数

转载 作者:行者123 更新时间:2023-12-04 15:19:48 26 4
gpt4 key购买 nike

需要写个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重置不是很可读。 Racket 惯用的做法是什么?

最佳答案

是否~v函数或 ~s函数来自 racket/format 为你工作?

> (~v 3)
"3"
> (~v "hello")
"\"hello\""
> (~v "hel\"lo")
"\"hel\\\"lo\""

关于整数和字符串的 Racket 转字符串函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34480558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com