Transform a natural number to a specific base and

2019-03-05 15:25发布

问题:

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

The next error appears:

expected: number?
given: '(0)
argument position: 2nd
other arguments...:
10

回答1:

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

It works as expected:

(num->base 12345 10)
=> '(1 2 3 4 5)


标签: scheme racket