haxtar
haxtar

Reputation: 2070

Scheme: number to string, string to list

I'd like to easily create a list of digits from an input number using Scheme's number->string and string->list functions.

This will code create the list of digits I want, but with one problem: #\ will precede each digit:

(define input 1234)

(define (digit-list input)
    (string->list (number->string input))
)

Running digit-list on input yields:

(#\1  #\2  #\3  #\4 )

How can I generate this digit list without the #\ preceding each digit?

Upvotes: 6

Views: 11086

Answers (1)

assefamaru
assefamaru

Reputation: 2789

The preceding #\ is scheme syntax for a character. You can convert each character to a number by first making it a string, then using string->number:

(number? (string->number (string #\1)))
=> #t

You can compose these two procedures, and map them onto your list as follows:

(map (compose string->number string)
     (string->list (number->string 1234)))
=> '(1 2 3 4)

Upvotes: 8

Related Questions