Scheme 数字的数字列表
我试图写一个函数,它接受一个数字并返回一个数字列表。例如:Scheme 数字的数字列表,scheme,lisp,Scheme,Lisp,我试图写一个函数,它接受一个数字并返回一个数字列表。例如: (list-num 648) ;=> (6 4 8) 我已经写了一些代码,但是它返回(8 4 6),并且我不能使用反向。到目前为止,我的代码是: (define (list-num n) (if (not (equal? (quotient n 10) 0)) (cons (modulo n 10) (list-num(quotient n 10))) (cons (modulo n 10) '())
(list-num 648)
;=> (6 4 8)
我已经写了一些代码,但是它返回(8 4 6)
,并且我不能使用反向
。到目前为止,我的代码是:
(define (list-num n)
(if (not (equal? (quotient n 10) 0))
(cons (modulo n 10) (list-num(quotient n 10)))
(cons (modulo n 10) '())))
您可以将函数用作内部函数,并包装一个执行相反操作的外部函数:
(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)))
然后
您还可以使用命名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))))))
在公共Lisp中:
CL-USER 21 > (map 'list #'digit-char-p (princ-to-string 648))
(6 4 8)
这可能是复制品。一些相关的问题包括:,这是另一个方向;这涉及到将数字转换为数字列表。我们来看看:这是的副本。
CL-USER 21 > (map 'list #'digit-char-p (princ-to-string 648))
(6 4 8)