Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number to list of digits

Tags:

scheme

racket

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.

like image 891
ceth Avatar asked Dec 10 '25 18:12

ceth


2 Answers

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

like image 172
Chris Jester-Young Avatar answered Dec 12 '25 12:12

Chris Jester-Young


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.

like image 41
user448810 Avatar answered Dec 12 '25 12:12

user448810



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!