我想将整数转换为列表。例如,2245 => (2 2 4 5)。
我不喜欢(coerce (write-to-string 2245) 'list)
,因为它会产生(#\2 #\2 #\4 #\5)
。
请帮忙吗?
答案 0 :(得分:5)
(map 'list #'digit-char-p (prin1-to-string n))
效果很好。
答案 1 :(得分:5)
(defun number-to-list (n)
(loop for c across (write-to-string n) collect (digit-char-p c)))
基于替代循环的解决方案。
答案 2 :(得分:2)
与jon_darkstar相同,但在常见的lisp中。这对于负数来说是失败的,但是很容易修改。
(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))))
答案 3 :(得分:2)
非负整数的Common Lisp实现:
(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)))))
答案 4 :(得分:1)
我并不真正使用普通的lisp,但我会在Scheme中这样做。希望这有帮助吗?
(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)