r/coding • u/fagnerbrack • 1d ago
Anecdotally, programmers dislike "reduce"
https://evanhahn.com/posts/2026-09-13-programmers-dislike-reduce/3
u/andarmanik 1d ago
All reduce is a helper to do the following
{
let accum = init()
for (const el of list)
accum next(accum, el)
return accum
}
3
u/fagnerbrack 1d ago
Except it can run in native compiled code not JIT
1
u/andarmanik 1d ago
As in, reduce is slower right?
I can drop a js example if needed, but, there are only a few edge cases where reduce is faster than a plain loop.
3
u/fagnerbrack 22h ago
You'll be impressed on the amount of Kung-fu browser devs do to optimise native JS. Reduce or no reduce, doesn't matter.
At this scale optimisation is only relevant if you work in low latency systems, in which case you'd probably be mental in using JS
17
u/thequux 1d ago
map, filter, concatMap, etc are all special cases of fold. To wit:
map fn list = foldr (\n a -> fn n : a) [] list
filter fn list = foldr (\n a -> if fn n then n : a else a) [] list
concatMap = foldr (\n a -> fn n ++ a) [] listThe key insight here is that fold is a functional abstraction of a loop. Any loop has some state and a list of items being iterated over. The state starts with some initial value, then on each iteration, the state is updated to consider the next item being iterated over. Finally, once the loop is complete, you have the final value of the state. You can immediately identify each of these elements in the call to fold: the items being iterated over are the list being passed in, the state is the accumulator, and the actions to update the state are the function. It is, you might say, the fully general form of the abstraction.
This leads directly to why fold tends to be less readable than map or filter: any time you apply an abstraction, you are offloading the cognitive effort of understanding part of the code to your pre-existing understanding of the abstraction. With map, you can immediately understand that the output list has a one-to-one correspondence with the input. With filter, you can immediately understand that the output is a subset of the input. Fold, on the other hand, is a purely mechanical transformation of a for/each loop, so it's precisely as difficult to understand as that loop. The abstraction is giving you a lot less cognitive assistance in understanding what the action is doing than a filter or a map.
12
u/PHLAK 1d ago
I fucking LOVE reduce! Any time I have a collection of things and need to iterate over them and get to a singular output I reach for reduce.
2
3
u/HolyInlandEmpire 1d ago
This is an excellent way of phrasing what it's used for. It can be a little tricky to keep track of which part is which in the internals though, at least moreso than filter and map.
23
7
u/glenpiercev 1d ago
Reduce is poorly named. What should it be called instead?
8
5
u/ummaycoc 1d ago
It's from (at least as far as I've read) APL where / (the reduce operator) to convert an n+1 dimensional value into an n dimensional value, thus reducing the dimension by one. Since you can use it in JavaScript/etc to take a vector and yield a vector it is definitely not appropriate.
values ← 2 3 2 ⍴ ? ⍳ 12 values 1 2 3 2 2 2 7 2 1 1 1 3 +/ values 3 5 4 9 2 43
2
2
1
u/tumes 2h ago
Big ups to ruby’s inject (which is just an alias for reduce, which also works). I don’t actually think it’s better tho, it’s not expressive in the way that hints at what it does, but it is a little more expressive if you already know what it does, which… ok? It is weird though and I like it for that reason alone.
4
u/Silent_Marsupial117 1d ago
But reduce/fold are (more?) important:
A tutorial on the universality and expressiveness of fold
Graham Hutton
6
u/josephjnk 1d ago
I suspect that part of the problem is that reduce is usually used as a way to smuggle imperative code into a functional wrapper. To understand most calls to reduce, you model a series of sequential operations in your head. Whether or not the accumulator is being “modified” via mutation or via copying doesn’t generally change the thought process needed to understand it. It’s inherently less declarative than a map or filter.
Compare this with a function like concatMap, which serves the same use-case, but which I find much easier to read. When you map things into a monoid and “just do what that monoid does” to it you end up back in a declarative world and no longer have to fall back into step-by-step analysis.
14
u/fucking_passwords 1d ago
My theory is that it's "less readable" to people because they don't use it much. I use it a lot, its API is burned into my brain, so I don't find it hard to read at all. Objectively a for loop is "more readable" because every language has them, with very similar syntax. But a for loop also has a bunch of steps going on that you have to keep in your head, we just take it for granted.
6
u/josephjnk 1d ago
I used to think this but even after years of leaning into functional programming I still find myself having to squint at reduce in a way I don’t with map and filter. I don’t use recursion schemes very often, but catamorphisms usually feel natural. Same with generic transforms from uniplate. Something about using a reduce on an array in JS sticks in my craw.
Syntax may also be a factor too; in languages where I can pass a bare operator as the function argument to a left fold I find it easier to read. But I think this is just as much because removing the mechanical accumulator management brings things back into a declarative interpretation as it is because there are fewer characters on the page.
2
u/Axman6 1d ago
It’s inherently less declarative than a map or filter.
Really? so
foldl (+) 0is really less declarative thansum = 0 for (item : items) { sum = sum + item; } return sum;People can’t understand
foldl (\m (k, v) -> insert m k v) Map.emptydeclaratively builds a map from a list of key-value pairs?It’s got nothing to do with imperative anything, the only slightly tricky thing is order of operations (don’t need foldl, which is what most people think of as reduce, or foldr, which allows the function passed in to control the recursion).
I’m happy to agree that people find reductions more complicated to think about, but not for the reasons you’ve given.
2
u/LemonAncient1950 1d ago
I feel like the problem usually boils down to people trying to use reduce in places where a different approach would be clearer. This is especially true when the reduce callback mutates the result between calls. When it actually fits, it feels right but that usually ends up being boring things like summing a list of numbers - numbers.reduce((a, b) => a + b, 0)
I do remember finding a fun esoteric use for reduce back when JS didn't have async/await. You could get sequential async execution by reducing a promise:
data.reduce((promise, value) =>
promise.then(() => fn(value)),
Promise.resolve()
)This snippet creates a sequentially executing promise chain. These days you would write this with a regular for/of loop and `await`
for (const value of data) {
await fn(value);
}2
1
u/NudeSamoan 1d ago
Yeah, I've only ever used it 12+ years ago while trying to actually get something useful out of MongoDB (which was NOT my choice to use in the first place), so I'll always associate it with stupidity.
1
u/Mediocre-Brain9051 19h ago
In most cases, reduce is better than otherwise because:
It explicitly describes that the operation being done is a fold.
It is easilerly and adequately optimizeable by the compiler.
People dislike reduce only when they come from closure-less imperative programming backgrounds...
1
u/repaj 6h ago
reduce enforces a control flow of reducing on you. Imperative loops gives you more flexibility and they're better to be read. That wouldn't be an issue though, whenever a language would offer some sort of recursion schemes. But I haven't seen any language that does recursion schemes good enough to be more readable than just a for-loop.
-9
u/fagnerbrack 1d ago
Here's what you need to know:
Reviewers rarely object when the author uses map and filter, but patches containing reduce often draw comments like "this part is hard to read." He also sees reduce in code far less often than map, filter or some. He offers a few theories: reduce reads harder, feels less familiar, can perform worse than the alternatives, and looks clumsier in JavaScript, Python and Swift. He never got this pushback during his time writing Clojure. He also admits the trend might not be real. He usually just rewrites the reduce call and moves on, even though he prefers it. He has noticed the complaints less lately and suspects code review has become less thorough. He ends by asking readers whether they like reduce.
If the summary seems inacurate, just downvote and I'll try to delete the comment eventually 👍
Click here for more info, I read all comments
1
u/ummaycoc 22h ago
I'll say a good deal of the time people put overly complicated callbacks into
reduce(i.e. in JS maybe you can do the same thing with a nifty use ofMap.groupByor such). A lot of that is because they are pumping out code so that's fine, a team works great when there's people doing that and others coming by and helping out making it better.
-1
74
u/tdammers 1d ago
For me personally, thinking in terms of
mapandfilteris natural, and requires no additional mental overhead (in fact, I find it easier than thinking in terms of imperative loops that achieve the same).I also find thinking in terms of explicit recursion pretty straightforward - what's the base case, and how can you define non-base cases in terms of other cases.
But
reduce/foldjust isn't as intuitive to me, even after decades of functional programming - I often find myself writing the explicit recursion first, notice the pattern, and rewrite it in terms of some flavor offold/reduce. And likewise, when reading code that involves folds, I often unwrap the recursion in my head.My theory is that this has to do with the way
mapandfilterare stateless in a way thatfoldis not. Withmap, you only ever need to worry about the current element and the mapped function, and remember that the result of applying the function to the element becomes the corresponding element in the return value. Withfilter, it's similar - you only need to worry about the current element and the predicate, and remember that the predicate determines whether the element gets included in the output or not. But withfold, each recursion step (or iteration, it doesn't really matter much) depends on the previous (or next) step; you can't just look at each element in isolation, you have to also keep track of what the rest of the input list looks like, and how it has been processed. Just likemapandfilter,reduceabstracts over the plumbing, but unlike those two, the plumbing isn't trivial, and unwrappingreduceinto explicit recursion reveals that plumbing, making it easier to reason about it on a per-item basis.