Convert number to list of digits

前端 未结 3 1071
滥情空心
滥情空心 2020-12-21 06:29

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 
          


        
3条回答
  •  执笔经年
    2020-12-21 06:55

    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.

提交回复
热议问题