3 ms·
Loops are intuitive and easy to understand, because they are concrete. They can also be cluttered and hard to read due to all the required bookkeeping. For sim
by jltsiren 5y ago
Loops are intuitive and easy to understand, because they are concrete. They can also be cluttered and hard to read due to all the required bookkeeping.
For simple loops, I prefer something like map/filter/fold when appropriate. I try to avoid chaining them, because that often turns the code impossible to understand and makes me feel stupid. If the loop can't be modeled naturally as a higher-order function, an iterator-based loop is easier to read than an index-based loop, which is better than tail recursion.
With complex loops, there is no way around concrete loops with comments describing the invariants and what each part of the iteration does.
Many problems can be modeled naturally with recursion. Such problems are particularly common with graphs. However, you should never use explicit language-level recursion unless you can guarantee that recursion depth will be small. It's easy to get a stack overflow, so recursion should usually mean a loop with an explicit stack of states.