Reduce is Not the Answer
TLDR
The reduce
function:
- can do anything, and often does…
- fails to communicate intent compared to its alternatives
reduce
is the for-loop of functional programming…
What is reduce?
The reduce function takes a collection, iterates over it, and generates a single value.
Depending on the language, it might also be called: fold, accumulate, aggregate, compress, or inject.
If you’re not already familiar with reduce
, let me punt to Google.
What’s the problem?
reduce
is just a for-loop, with some “accumulator”. When the accumulator is a list/map, things can get complicated pretty fast.
Here’s a for-loop:
And here’s the same code as a reduce
:
What COULD this code do? 🤔
Anything, really.
It could be a map
or a filter
, or some terrible combination of both or neither.
My Point: reduce is too low-level
A for-loop can do anything and reduce
has the same lack of clarity and intent… because it is a
building block:
Reduce (sometimes called fold) is a basic building block in functional programming. Almost all of the functions in the Enum module can be implemented on top of reduce. 1
But a pile of building materials is not a house.
A reduce
, given an anonymous function, is similar to tricky, inlined, and uncommented code.
It’s a missed opportunity to extract that logic to a function and give it a name.
But first…
Alternatives
That reduce
is probably not a special case, and it’s probably one of these:
If you use a functional language 2, refer to its excellent “enumerable” module:
What’s Next?
In my next post 3, I’m going to cover reduce
anti-patterns.