3 ms·
Yeah, the "problem" with reduce is that it can do anything, and so doesn't offer much over a traditional for loop with mutable local variables to accumulate int
by Quekid5 1y ago
Yeah, the "problem" with reduce is that it can do anything, and so doesn't offer much over a traditional for loop with mutable local variables to accumulate into. Of course, if you can replace a reduce() with a filter and/or map or whatever (which more clearly states intent), by all means do so!
If you really need arbitrary computation, I'm not sure there's any real readability benefit to reduce() over local mutation (emphasis on local!). Sure, there's immutability and possibly some benefit to that if you want to prove your code is correct, but that's usually pretty marginal.
- lblume 1y agoReduce can be very useful to signal that the state used is inherently limited. My rule of thumb is to use reduce when the state is a primitive or composed of at most two primitives, and a for loop otherwise. What counts as "primitive" depends on the language of choice and abstraction level of the program, of course.
- Quekid5 1y agoFair observation, but just opening a local lexical scope (in an expression-oriented language) can help with that. Also ... something something ST monad :)