Coercing numbers to lists in common lisp
I'd like to turn integers into l开发者_如何学JAVAists. For example, 2245 => (2 2 4 5).
I dislike (coerce (write-to-string 2245) 'list)
because it yields (#\2 #\2 #\4 #\5)
.
Help please?
(map 'list #'digit-char-p (prin1-to-string n))
works well.
(defun number-to-list (n)
(loop for c across (write-to-string n) collect (digit-char-p c)))
An alternative loop based solution.
Same as jon_darkstar but in common lisp. This fails for negative numbers, but trivial to amend.
(defun number-to-list (number)
(assert (and (integerp number)
(>= number 0)))
(labels ((number-to-list/recursive (number) (print number)
(cond
((zerop number)
nil)
(t
(cons (mod number 10)
(number-to-list/recursive (truncate (/ number 10))))))))
(nreverse (number-to-list/recursive number))))
Common Lisp implementation for non-negative integers:
(defun number-to-list (n &optional tail)
(if (zerop n)
(or tail '(0))
(multiple-value-bind (val rem)
(floor n 10)
(number-to-list val (cons rem tail)))))
I don't really use common lisp, but I'd do it like this in Scheme. hopefully that can help?
(define (number-to-list x)
(define (mod-cons x l)
(if (zero? x)
l
(mod-cons (quotient x 10) (cons (remainder x 10) l))))
(mod-cons x '()))
(number-to-list 1234)
A variation on @Mark Cox's solution that also includes the '-' sign in case of negative integers. Inspired by @Terje Norderhaug's amendment to @rhombidodecahedron's solution, where negative numbers are represented by including a negative sign before the digits.
(defun number-to-numlist (number)
"Converts an integer to a list of its digits. Negative numbers
are represented by a '-' sign prepended to the digits of its absolute value."
(assert (integerp number))
(labels ((collect-digits (number number-components list-of-numbers)
(setf number-components (multiple-value-list (floor number 10)))
(if (zerop number)
(or list-of-numbers '(0))
(collect-digits (first number-components) nil
(cons (second number-components) list-of-numbers)))))
(let ((number-list (collect-digits (abs number) nil nil)))
(if (< number 0)
(append '(-) number-list)
number-list))))
精彩评论