Simple trampoline implementation for stackless recursion in Java
github.com
github.com
I mean, I understand explicit trampolining in Clojure, but in Java you don't often use recursion.
But there is already a sub-project to support TCO in JVM (but it is very old and progress is very slow...why? I think that's because recursion is rare in Java-world. Nobody actually need this):
http://openjdk.java.net/projects/mlvm/subprojects.html
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6804517
Aaand AFAIK it is very difficult (impossible?) to do automatic TCO in OOP languages. Check https://archive.is/FfmYF:
But although it is well known how to automatically transform a tail-recursive function into a simple loop, the Java specification doesn't require that this transformation be made. Presumably, one reason it is not a requirement is that, in general, the transformation can't be made statically in an object-oriented language. Instead, the transformation from tail-recursive function to simple loop must be done dynamically by a JIT compiler.
As long as it is an essential part of the compilation semantics, the description "Optimization" is IMHO unwarranted.
Consider the following C program:
long long i; /* assume 64 bit */
for (i=0;i>=0;++i) {
if ((i*i*i -(i>>12) +(i>>24) -(i>>36) +(i>>48))%3819 == 5) {
printf("found an example: %64i\n", i);
}
}
It is not directly useful itself, but variations on it are (e.g. hash cash proof of work computations are not dissimilar). It will run practically forever on every machine on which "long long" is 64 bits. It will likely terminate in finite time on a machine in which "long long" is 32 bit (there's undefined C overflow behaviour, so it might never terminate). And it will do so with zero additional space.A tail-call equivalent (the only kind of loop available in Scheme, for example) will -- without TCE/TCO -- overflow the stack on a 64-bit integer-or-more (e.g. Scheme's arbitrary precision numbers) on every machine built so far. It will likely do the same even if ints are limited to 32 bit - although a machine with >16GB ram is likely to complete a 32 bit run with reasonably optimized language runtime and stack allocation scheme (neither of which is common - x64 ABI red zones would require >128GB just to do the 32 bit count with full stack frames).
If the int goes to 128 bit, all the memory chips ever produced in the world (and likely all those that will be produced in the next 20 years) would not be enough to stop this program from overflowing its stack - much unlike a TCE/TCO/C version.
In my opinion, something that switches between bounded and unbounded memory requirements should not be called "optimization", but to I guess to each their own.