将自然数转换为特定的基数并将其 return 作为列表

Transform a natural number to a specific base and return it as a list

我想将函数的结果显示为列表而不是数字。 我的结果是:

(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

我觉得你得重新考虑这个问题了。将结果附加到全局变量绝对不是要走的路,让我们通过尾递归尝试一种不同的方法:

(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)