Scheme: number to string, string to list
Asked Answered
S

1

6

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?

Sungkiang answered 19/3, 2018 at 1:43 Comment(0)
S
8

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)
Saucy answered 19/3, 2018 at 1:55 Comment(1)
Awesome, thank you very much! For some reason, the compose function was not defined in my environment but using the link you gave, I could find it: (define (compose f g) (lambda (x) (f (g x)))) and it worked!Sungkiang

© 2022 - 2024 — McMap. All rights reserved.