4 ms·
Tail calls and while loops are essentially equivalent, so why care whether a language prefers one or the other?
by creata 5y ago
Tail calls and while loops are essentially equivalent, so why care whether a language prefers one or the other?
- gleenn 5y agoBecause if you like functional programming, then avoiding loops and imperative code is desirable. Some of us hate seeing `for` and `while` because they also imply mutation of variables. Recursion is beautiful.
- Vetch 5y agoIt's like, why use one synonym and not the other? Sometimes it's because writing things in an immutable manner makes things clearer. Other code that can benefit are certain coroutines and generators.
- creata 5y ago> It's like, why use one synonym and not the other? Sometimes it's because writing things in an immutable manner makes things clearer. That's true in many situations, but in this case the equivalence between the two is so straightforward that I can't see recursion gaining you any clarity. Perhaps you have a concrete example?
- Vetch 5y agoI can't think of a specific example but I do know that there have been times where I have chosen to write a loop as tail recursion and times where I have used mutable variables and a while loop. Why one or the other might be recursion better capturing intent, preferring immutability, efficiency or just a matter of taste. Sometimes it makes more sense and is more flexible to package functionality as a recursive function, then mutation and variables feel like clutter. Other sometimes using recursion instead of a loop gains nothing expressively. Or sometimes structural recursion + pattern matching is the much more elegant approach in terms of communicating and capturing the essence of the algorithm.
- jhgb 5y agoThey're not "essentially equivalent". A while loop can't begin in one module and end in another. A tail call sequence can. Loops are not modular.
- creata 5y agoJust to be clear, are you suggesting mutual recursion across modules?
- krastanov 5y agoWhy is that unreasonable? I might be missing something (I have no formal CS education), but I can imagine it, e.g. a base graph datastructure library, and then two libraries dependent on the base library being used together for some graph traversal work (where callbacks are used).
- jhgb 5y agoJust to be clear, I'm using the word "module" here in an extremely generic, language independent way. Basically in the sense of "things that can be compiled individually". In many languages (for example in Lisp), those are functions. A syntactic loop construct ordinarily can't even cross a function boundary. If your language of choice features formalized modules in the Modula-2 sense, its loops most likely can't span multiple functions even within a single Modula-2-sense module, even if you wanted that (for example, in a state machine with named states as functions which tail-call each other to switch state by transferring control, or something like that).