简体   繁体   中英

How can I transform this code into Racket/ Scheme

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; 
    }   

eg 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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM