本文介绍了将自然数转换为特定的基数并将其作为列表返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将函数的结果显示为列表而不是数字.我的结果是:
I want to show the result of my function as a list not as a number. My result is:
(define lst (list )) (define (num->base n b) (if (zero? n) (append lst (list 0)) (append lst (list (+ (* 10 (num->base (quotient n b) b)) (modulo n b))))))出现下一个错误:
expected: number? given: '(0) argument position: 2nd other arguments...: 10 推荐答案我认为你必须重新考虑这个问题.将结果附加到全局变量绝对不是要走的路,让我们通过尾递归尝试不同的方法:
I think you have to rethink this problem. Appending results to a global variable is definitely not the way to go, let's try a different approach via tail recursion:
(define (num->base n b) (let loop ((n n) (acc '())) (if (< n b) (cons n acc) (loop (quotient n b) (cons (modulo n b) acc)))))它按预期工作:
(num->base 12345 10) => '(1 2 3 4 5)更多推荐
将自然数转换为特定的基数并将其作为列表返回
发布评论