我正在尝试编写一个函数,它接受一个数字并返回该数字的数字列表。例如:
(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) '())))
发布于 2014-02-25 16:24:51
您可以使用您的函数作为内部函数,并包装一个执行相反操作的外部函数:
(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))))))
发布于 2014-02-25 20:24:21
共有的Lisp:
CL-USER 21 > (map 'list #'digit-char-p (princ-to-string 648))
(6 4 8)
https://stackoverflow.com/questions/22019634
复制相似问题