How can I transform this code into Racket/ Scheme

一个人想着一个人 提交于 2020-03-25 19:15:06

问题


This is the code I want translated into Racket:

public static ArrayList<Integer> convert(int k, int n) {
        ArrayList<Integer> lst = new ArrayList<>();
        while (k / n != 0) {
            lst.add(k % n); 
            k = k/n;
        }
        lst.add(k % n);
        return lst; 
    }   

e.g. in Racket the (convert 23 2) should return the binary of the decimal 23, which is (list 1 0 1 1 1).

This is what I got so far:

(define (convert k n)
  (cond 
    [(> (/ k n) 0) (list(modulo k n))]
    [else  0] 
))

It works for the first element of the list.

Thanks for any help!


回答1:


Be aware that the / operator in Java performs integer division, so in Racket you'd have to use quotient to obtain the same effect.

This is a good opportunity to use a named let to implement the loop, as the result list needs to be accumulated in reverse. Other than that, the solution is pretty straightforward:

(define (convert k n)
  (let loop ((k k) (acc '()))
    (if (zero? (quotient k n))
        (cons (modulo k n) acc)
        (loop (quotient k n) (cons (modulo k n) acc)))))

For example:

(convert 23 2)
=> '(1 0 1 1 1)


来源:https://stackoverflow.com/questions/59993838/how-can-i-transform-this-code-into-racket-scheme

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