How do I convert a number to a list of digits?
I am currently doing:
;; (num->list 12345) -> '(1 2 3 4 5)
(define (num->list n)
(local
((define (num->list n)
(map (lambda (c)
(char->num c))
(string->list (number->string n))))
(define (char->num c)
(- (char->integer c) 48)))
(num->list n)))
but would like to know if there's a better way.
Here's how I'd do it in Racket:
(require srfi/1 srfi/26)
(define (digits->list num (base 10))
(unfold-right zero? (cut remainder <> base) (cut quotient <> base) num))
This is the sort of problem unfold was designed for. :-D
This is the digits function of my Standard Prelude:
(define (digits n . args)
(let ((b (if (null? args) 10 (car args))))
(let loop ((n n) (d '()))
(if (zero? n) d
(loop (quotient n b)
(cons (modulo n b) d))))))
Your version of the function goes back-and-forth between strings and numbers; my version is purely arithmetic. My version also provides for bases other than decimal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With