3 ms·
Recursion indeed can be useful when working with trees or graphs. However, I don't like using recursion instead of a loop, because you make reader to unroll you
by codedokode 4y ago
Recursion indeed can be useful when working with trees or graphs. However, I don't like using recursion instead of a loop, because you make reader to unroll your code in their head to understand what it really does. If you need to add two arrays of numbers, use loop or array addition, but don't use recursion as a replacement for a loop.
Sadly the article uses a poor example, writing a useless factorial function. I have never needed such a function in production code, and if I needed, I would write it using a loop. Using bad examples like this might create an impression that recursion is not useful in real code (which is wrong). It would be better if you have used an example that looks like real code and that would become less readable without recursion.
- RHSeeger 4y ago> If you need to add two arrays of numbers, use loop or array addition There are plenty of algorithms that make more sense when expressed using recursion. Iterating over a list of numbers generally isn't one of them. But walking a tree is a good example.
- kmeisthax 4y agoMore specifically: if you don't want to recursively iterate a tree, you have to hold a list of prior nodes to return to anyway... which is no different from weaving that information into the stack. Non-recursive iteration in this case literally requires you to emulate the recursion.
- vbezhenar 4y agoThose algorithms usually use non-tail recursion. Most tail recursion uses usually is trivial to rewrite in a loops.
- wtetzner 4y ago> Most tail recursion uses usually is trivial to rewrite in a loops. Except for tail calls that aren't self-calls. Which for code I write is actually fairly frequent.
- jagger27 4y agoReadability is really not a relevant factor for WebAssembly. Having tail-call recursion support is critical for the languages that compile to Wasm that use tail-calls themselves.