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