13 ms·
I was thinking about this recently: is there ever a reason to put recursion in an everyday “workman” code base? Seems like it would be so out of place in a rea
by jpeg_hero 7y ago
I was thinking about this recently: is there ever a reason to put recursion in an everyday “workman” code base?
Seems like it would be so out of place in a real industry code base, like a infinite loop waiting to happen. There are always better more readable and maintainable ways to accomplish the same thing.
- pjc50 7y agoThere are contexts where it's banned (MISRA, and other embedded scenarios). But it's very hard to work with tree structures without recursion - if you're not careful you just end up with an explicit stack rather than using the software stack. In situations where you think auto-vectorisation might help, you definitely want to do it as iteration. This is partly why I like the system of transformers that LINQ is built out of; you can specify your query in a natural nice functional manner, and then let the optimizer convert it into a fast query.
- yen223 7y agoLoops are also infinite loops waiting to happen, yet we still use them :) The reason one might want to use recursion is when you're working on a data structure that is recursive in shape, like trees. And trees are very common, the Hacker News comments are one such example.
- Smaug123 7y agoSure there is: it lets you express loops immutably. Rather than `state := null; while condition do: mutate-state-and-recompute-condition`, you can do `let loop(state) = if shouldContinue(condition) then loop(newState) else resultOfTheLoop`. Rely on the tail-call optimiser to compile this to a genuine imperative loop. This looks very odd the first few times you see it, but it's much harder to get wrong.