3 ms·
> Note that neither the Microsoft C# compiler nor the Mono one emit tail calls The F# compiler does, and not just for self-recursive calls. > the MS .NET Just
by bad_user 17y ago
> Note that neither the Microsoft C# compiler nor the Mono one emit tail calls
The F# compiler does, and not just for self-recursive calls.
> the MS .NET Just-In-Time compiler however transforms tail recursion to loops
The hard problem is to have mutually recursive functions ... A() calls B() calls C() calls A().
I'm currently working on a compiler that behind the scenes implements trampolines, so if you had something like ...
int methodA() {
// does something here
return methodB("calling B");
}
This would be translated to something like (pseudocode) ...
int methodA(TailCallException ex) {
// do something here
ex.method = methodB;
ex.args = [ 'calling B' ];
throw ex;
}
// trampoline implemented for any method with tail-calls
int methodA() {
int result;
has_next = true;
method = reference to methodA;
args = []
// reusing the same TailCallException instance
exc = new TailCallException();
while (has_next) {
try {
result = method.invoke(args, exc);
has_next = false;
}
catch (TailCallException ex) {
method = ex.method;
args = ex.args;
}
}
return result;
}
So yeah, it's possible. But this is overkill for functional languages where you've got recursion all over the place.