整数和字符串的racket to-string函数

Alb*_*ymk 1 racket

需要编写一个to-string接受整数和字符串的函数.

(to-string 3) ; -> "3"
(to-string "hello") ; -> "\"hello\""
(to-string "hel\"lo") ; -> "\"hel\\\"lo\""
Run Code Online (Sandbox Code Playgroud)

我设法这样做:

(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")
Run Code Online (Sandbox Code Playgroud)

但是,get-output-bytes重置不是很易读.什么是惯用的球拍方式呢?

Ale*_*uth 5

~v功能或~s功能是否racket/format适用于您?

> (~v 3)
"3"
> (~v "hello")
"\"hello\""
> (~v "hel\"lo")
"\"hel\\\"lo\""
Run Code Online (Sandbox Code Playgroud)


vrs*_*vrs 5

我不确定~v~s函数是否仍然需要racket/format#lang racket,但您可以使用甚至format适用于racket/base

#lang racket/base
(format "~v" 3)
(format "~v" "hello")
(format "~v" "hel\"lo")
Run Code Online (Sandbox Code Playgroud)

这正是您所需要的:

"3"
"\"hello\""
"\"hel\\\"lo\""
Run Code Online (Sandbox Code Playgroud)