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

时间:2015-12-27 12:51:30

标签: racket

需要编写一个接受整数和字符串的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重置不是非常易读。什么是惯用的球拍方式呢?

2 个答案:

答案 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

details
racket/base

这可以满足您的需求:

#lang racket/base
(format "~v" 3)
(format "~v" "hello")
(format "~v" "hel\"lo")