Convert number to list of digits

前端 未结 3 1059
滥情空心
滥情空心 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.

    0 讨论(0)
  • 2020-12-21 07:08

    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

    0 讨论(0)
  • 2020-12-21 07:15

    "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.


    1. Even at the expense of incorrect behavior for some corner cases -- e.g., as-is, it only even attempts to work correctly for strictly positive numbers.
    0 讨论(0)
提交回复
热议问题