帮我把这个 Java 翻译成Scheme,让我脑子里的事情顺利进行
我正在学习Scheme,并且已经阅读了基础知识,但我仍然不知道如何将Java 类“映射”到Scheme 代码。你们有人能帮我吗?我只需要有人向我展示这在计划中的样子,以掌握最终的细节并让事情在我的脑海中进行:
public class sumFibonacciValues {
public static void main(String [] args) {
int n = 4000000;
long i2 = 1, i1 = 1, Fibo = 0, temp = 1;
while(i2 < n) {
temp = i1 + i2;
i1 = i2;
i2 = temp;
if(i2 % 2 == 0)
Fibo += i2;
}
System.out.println(Fibo);
}
}
I am learning Scheme, and I've read the basics but I still can't figure how to "map" a Java class to Scheme code. Could any of you guys help me out here? I just need someone to show me how this looks in Scheme to grasp the final details and get things going in my head:
public class sumFibonacciValues {
public static void main(String [] args) {
int n = 4000000;
long i2 = 1, i1 = 1, Fibo = 0, temp = 1;
while(i2 < n) {
temp = i1 + i2;
i1 = i2;
i2 = temp;
if(i2 % 2 == 0)
Fibo += i2;
}
System.out.println(Fibo);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不会回答看起来很像家庭作业的问题,但“惯用”评论只是要求证明它实际上并不那么远。首先,直接翻译:
其次,通过删除冗余突变,使其变得“惯用”,而只是绑定新值,并使用尾递归循环。请注意,此代码仍然与原始代码直接相关:
最后,现在代码更加清晰,您可以看到存在一些冗余。这是一个清理后的版本:
请注意,可以对 Java 代码进行相同的清理。 (但这确实留给读者作为练习......)
I wouldn't have answered something that looks so much like homework, but the "idiomatic" comment just begged for a demonstration that it's really not that far. First, a direct translation:
Second, make it "idiomatic", by removing the redundant mutations, and instead just bind new values, and using a tail-recursive loop. Note that this code is still in direct correlation with the original:
Finally, now that the code is clearer, you can see that there are some redundancies. Here's a cleaned up version:
Note that the same cleanup can be done on the Java code. (But that's really left as an exercise to the reader...)