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
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.
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
"Better" is always open to definition, but a bit more direct/obvious way would be something like this:
(define (int->list n) (if (zero? n) `()
(append (int->list (quotient n 10)) (list (remainder n 10)))))
As to whether this is "good", "bad", "better", etc., I guess it depends on what you want. There's no question that you can find code that's more efficient, more versatile, etc. (in fact, @user448810 has already posted some). This is more what I'd think of as example code for something like an introduction to Scheme -- the emphasis is on being simple and easy to understand/explain1. I'd expect that almost anybody with a bare minimum of exposure to some Lisp-like language and a general idea of how such numeric conversion is done should be able to figure out everything that's going on here fairly quickly/easily.