如何将此代码转换为 Racket/Scheme [英] How can I transform this code into Racket/ Scheme
问题描述
这是我想翻译成 Racket 的代码:
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;
}
例如在 Racket 中,(convert 23 2)
应该返回十进制 23 的二进制,即 (list 1 0 1 1 1)
.
e.g. in Racket the (convert 23 2)
should return the binary of the decimal 23, which is (list 1 0 1 1 1)
.
这是我目前得到的:
(define (convert k n)
(cond
[(> (/ k n) 0) (list(modulo k n))]
[else 0]
))
它适用于列表的第一个元素.
It works for the first element of the list.
感谢您的帮助!
推荐答案
请注意 Java 中的 /
运算符执行整数除法,因此在 Racket 中您必须使用 quotient
以获得相同的效果.
Be aware that the /
operator in Java performs integer division, so in Racket you'd have to use quotient
to obtain the same effect.
这是一个使用命名的let
来实现循环的好机会,因为结果列表需要反向累加.除此之外,解决方案非常简单:
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)))))
例如:
(convert 23 2)
=> '(1 0 1 1 1)
这篇关于如何将此代码转换为 Racket/Scheme的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!