4 ms·
Loops can be written as recursive functions, so that the compiler can use TCO to turn them back into loops... If your language religiously omits loops, it's un
by mantrax5 12y ago
Loops can be written as recursive functions, so that the compiler can use TCO to turn them back into loops...
If your language religiously omits loops, it's understandable why you'd need to emulate loops this way, but the alternative solution is: have loops in the language.
This leaves us with continuations, which is a great hack, but again, a hack, for languages which don't implement fibers/coroutines/generators natively (see Python generators, see C# await/async, etc.).
This is not the path we have to go down to. Layering hacks upon hacks, so we can implement other hacks on top of it.
If we need loops, have a language with loops. If we need coroutines, the language should implement coroutines.
- RHSeeger 12y agoThere are a number of algorithms that, while able to be expressed as loops, are more succinctly expressed recursively. Obviously, the reverse is also true, but having both options in the language means there are more cases where the code is a cleaner expression of the algorithm being implemented.
- mantrax5 12y agoThe problem with this is that not every recursion qualifies for a TCO optimization, and when it doesn't, you're in big doodoo if your recursion goes deep. This means a programmer has to tell apart two types of recursion based on how a compiler optimizes them. It's possible to learn, but this qualifies as a "leaky abstraction". It's far better to use loops when you want to loop, and recursion when you want to recurse, and if the compiler happens to use TCO, so be it. But don't rely on TCO. Instead, we see here whole algorithms which depend on TCO to work without filling up the stack. It's a path towards more obscure code, not more succinct code.
- rapala 12y agoIt's dead simple to tell apart a tail call. Does it look like return call(a, r, g, s) It is also very simple to test if the compiler does TCO. Just write def f(a): return f(a + 1) f(0) and wait for a stack overflow.
- justincormack 12y agoThat gives an indication, but not if it sometimes does TCO but not always (like gcc for C).
- lomnakkus 12y agoThe point here is the guarantee -- as specified by the language standard. There is no guarantee for TCO in C. The ES6 standard only guarantees the TCO for certain constructs which rapala's example showed (informally).