racket to-string function for integer and string
Asked Answered
G

3

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?

Geddes answered 27/12, 2015 at 12:51 Comment(0)
P
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\""
Photogene answered 27/12, 2015 at 14:34 Comment(0)
G
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\""
Guam answered 30/12, 2015 at 17:41 Comment(1)
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.Geddes
S
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))
     
  )
Satellite answered 16/4, 2022 at 22:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.