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

若如初见. 提交于 2019-12-20 06:12:33

问题


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)


来源:https://stackoverflow.com/questions/35629798/transform-a-natural-number-to-a-specific-base-and-return-it-as-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!