'Convert a string to list
Calling all racket developers, I am a newbie in the language of racket. I want to convert a string to a list.
I have a string like this:
"(1 2 3 4 5)"
I want to converted to:
'(1 2 3 4 5)
I tried using string-> list but this is the result:
(#\(
#\1
#\space
#\2
#\space
#\3
#\space
#\4
#\space
#\5
#\))
Solution 1:[1]
Here's one possible way, using Racket's read.
#lang racket
(define (convert str)
(with-input-from-string str
read))
(convert "(1 2 3 4 5)") ;=> '(1 2 3 4 5)
Normally, (read) will read an input from standard input. However, I use with-input-from-string to redirect the read operation on a string instead.
Solution 2:[2]
Here we split the string while ignoring the non-digits, then convert the digits to numbers:
#lang racket
(define (convert str)
(map string->number (string-split str #px"[ )()]")))
(convert "(1 2 3 4 5)")
; => '(1 2 3 4 5)
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 | Sorawee Porncharoenwase |
| Solution 2 | frayser |
