数字的数字列表

时间:2014-02-25 16:02:12

标签: scheme lisp

我正在尝试编写一个函数,它接受一个数字并返回一个数字的数字列表。例如:

(list-num 648)
;=> (6 4 8)

我已编写了一些代码,但它返回(8 4 6),我无法使用reverse。我的代码到目前为止:

(define (list-num n)
  (if (not (equal? (quotient n 10) 0))
      (cons (modulo n 10) (list-num(quotient n 10)))
      (cons (modulo n 10) '())))

2 个答案:

答案 0 :(得分:1)

你可以使用你的函数作为内部函数并包装一个反向的外部函数:

(define (list-num n)
  ; inner function - your initial function      
  (define (sub n)
    (if (not (equal? (quotient n 10) 0))
        (cons (modulo n 10) (sub (quotient n 10)))
        (cons (modulo n 10) '())))
  ; call inner function
  (reverse (sub n)))

然后

> (list-num 648)
'(6 4 8)

您还可以使用名为let 的和累加器:

(define (list-num n)
  (let loop ((n n) (acc '())) ; named let, acc=accumulator
    (let ((q (quotient n 10)) (r (remainder n 10)))
      (if (= q 0)
          (cons r acc)
          (loop q (cons r acc))))))

答案 1 :(得分:1)

在Common Lisp中:

CL-USER 21 > (map 'list #'digit-char-p (princ-to-string 648))
(6 4 8)