3 ms·
I wouldn't replace loops with recursion, generally speaking. It's probably at least as hard to write and understand explicit recursion as it is a for loop, and
by acjohnson55 8y ago
I wouldn't replace loops with recursion, generally speaking. It's probably at least as hard to write and understand explicit recursion as it is a for loop, and it's still fairly prone to off-by-one errors.
Explicit loops have a use, as does explicit recursion, but in the vast majority of cases, I use higher-order functions, like map, filter, flatmap, and fold.
The real problem is choosing tools that have more power than you need. This increases the surface area for potential bugs and it requires future reader to parse more code that's just there for plumbing.
- bachmeier 8y ago> it's still fairly prone to off-by-one errors. Can you explain this further? If you want to work your way through an array, for instance, you return once you have an empty array. If your result is stored in a data structure that can be appended, I don't see how it's possible to have an off-by-one error. You must be referring to another use case.
- acjohnson55 8y agoYeah -- in some nontrivial recursive situations, you might have multiple base cases or different 0 and 1 cases. I've just often run into situations where testing my algorithm reveals that one of the cases isn't exactly right, and therefore the result doesn't match expectations. It's much more difficult to get a `map` wrong, though. What could possibly go awry? I guess the moral is, more power, more responsibility, so it's best to save power for when you absolutely need it.