8

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?

3 Answers 3

9

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\""
Sign up to request clarification or add additional context in comments.

Comments

5

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\""

1 Comment

Thank you for the info. FYI, ~v works ok with bare #lang racket, docs.racket-lang.org/search/index.html?q=~v Still, I could use format if I want to cut down the dependency. Thanks again.
0

Using format works, but there are problems. there's no guarantee that what you've been passed is actually a string or an integer. It could be a list or a hash or whatever.

Here's a function to convert an integer or string to a string and raise a contract violation if you tried to do something unexpected like pass in a hash.

You could easily extend this to allow any number by changing the integer? to number? in the contract.

#lang racket

(define/contract (int-or-string->string var)
  (-> (or/c string? integer?) string?)
  (if (string? var)
      var
      (number->string var))
     
  )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.