Convert number to list of digits

删除回忆录丶 提交于 2019-12-18 09:01:38

问题


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.


回答1:


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.




回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/8014453/convert-number-to-list-of-digits

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!