'racket to-string function for integer and string
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?
Solution 1:[1]
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\""
Solution 2:[2]
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\""
Solution 3:[3]
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))
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alex Knauth |
Solution 2 | |
Solution 3 | masukomi |