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

后端 未结 1 794
抹茶落季
抹茶落季 2021-01-27 22:07

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 ls         


        
相关标签:
1条回答
  • 2021-01-27 22:13

    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)
    
    0 讨论(0)
提交回复
热议问题