I'd like to turn integers into lists. For example, 2245 => (2 2 4 5).
I dislike (coerce (write-to-string 2245) 'list)
because it yields (#\2 #\2 #\4 #\5)
.
Help please?
I'd like to turn integers into lists. 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.
(map 'list (lambda (c)(or (digit-char-p c) '-)) (prin1-to-string n))
Apr 7, 2011 at 4:40
(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)
quotient
(integer division). just tested in the interpreter, it works
Apr 5, 2011 at 23:10
(= x 0)
instead of (zero? x)
??
Apr 5, 2011 at 23:13
(loop ...)
??