列出方案编号 [英] Scheme number to list
问题描述
我需要为我的程序编写一个子程序,该程序需要使用一个整数,例如34109,并将其放入包含元素3、4、1、0、9的列表中.该整数可以是任何长度.有人对此有把戏吗?我已经考虑过在每个地方都使用模,但是我不认为它应该那么复杂.
I need a subroutine for my program written in scheme that takes an integer, say 34109, and puts it into a list with elements 3, 4, 1, 0, 9. The integer can be any length. Does anyone have a trick for this? I've thought about using modulo for every place, but I don't think it should be that complicated.
推荐答案
The simplest way I can think of, is by using arithmetic operations and a named let
for implementing a tail-recursion:
(define (number->list num)
(let loop ((num num)
(acc '()))
(if (< num 10)
(cons num acc)
(loop (quotient num 10)
(cons (remainder num 10) acc)))))
或者,您可以使用字符串操作解决此问题:
Alternatively, you can solve this problem using string operations:
(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))))
可以将其压缩为单个函数,但是我相信如果将问题分成上述子部分,则更容易理解.
This can be compressed into a single function, but I believe it's easier to understand if we split the problem in subparts as above.
(define (number->list num)
(map (lambda (c) (- (char->integer c) (char->integer #\0)))
(string->list
(number->string num))))
无论如何,结果是预期的:
Anyway, the results are as expected:
(number->list 34109)
> '(3 4 1 0 9)
这篇关于列出方案编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!