我需要写入方案用于我的程序的子程序,它接受一个整数,表示34109,并与元件3,4,1,0将其放入一个列表,9.整数可以是任何长度。 有没有人有此一招? 我想过用模的每一个地方,但我不认为它应该是复杂的。
Answer 1:
我能想到的最简单的方法,是用算术运算和一个名为let
用于实现尾递归:
(define (number->list num)
(let loop ((num num)
(acc '()))
(if (< num 10)
(cons num acc)
(loop (quotient num 10)
(cons (remainder num 10) acc)))))
另外,您也可以使用字符串操作解决这个问题:
(define char-zero (char->integer #\0))
(define (char->digit c)
(- (char->integer c) char-zero))
(define (number->list num)
(map char->digit
(string->list (number->string num))))
这可以被压缩成一个单一的功能,但我认为这是比较容易理解,如果我们在子部分划分为上述问题。
(define (number->list num)
(map (lambda (c) (- (char->integer c) (char->integer #\0)))
(string->list
(number->string num))))
无论如何,与预期一致的结果:
(number->list 34109)
> '(3 4 1 0 9)
Answer 2:
事情是这样的:
(define (num2list-helper num lst)
(cond ((< num 10) (cons num lst))
(else (num2list-helper (floor (/ num 10)) (cons (modulo num 10) lst)))))
(define (num2list num)
(num2list-helper num '()))
(num2list 1432)
作为itsbruce评论,你可以躲在里面最主要的一个辅助函数:
(define (num2list num)
(define (num2list-helper num lst)
(cond ((< num 10) (cons num lst))
(else (num2list-helper (floor (/ num 10)) (cons (modulo num 10) lst)))))
(num2list-helper num '()))
(num2list 1432)
未完待续...
Answer 3:
I'm not a fan of manual looping, so here's a solution based on unfold (load SRFI 1 and SRFI 26 first):
(define (digits n)
(unfold-right zero? (cut modulo <> 10) (cut quotient <> 10) n))
This returns an empty list for 0, though. If you want it to return (0)
instead, we add a special case:
(define (digits n)
(case n
((0) '(0))
(else (unfold-right zero? (cut modulo <> 10) (cut quotient <> 10) n))))
Of course, you can generalise this for other bases. Here, I implement this using optional arguments, so if you don't specify the base, it defaults to 10:
(define (digits n (base 10))
(case n
((0) '(0))
(else (unfold-right zero? (cut modulo <> base) (cut quotient <> base) n))))
Different Scheme implementations use different syntaxes for optional arguments; the above uses Racket-style (and/or SRFI 89-style) syntax.
文章来源: Scheme number to list