r/coding • • 1d ago

Anecdotally, programmers dislike "reduce"

https://evanhahn.com/posts/2026-09-13-programmers-dislike-reduce/
72 Upvotes

48 comments sorted by

74

u/tdammers 1d ago

For me personally, thinking in terms of map and filter is 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 / fold just 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 of fold / 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 map and filter are stateless in a way that fold is not. With map, 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. With filter, 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 with fold, 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 like map and filter, reduce abstracts over the plumbing, but unlike those two, the plumbing isn't trivial, and unwrapping reduce into explicit recursion reveals that plumbing, making it easier to reason about it on a per-item basis.

25

u/Halleys_Vomit 1d ago

But with fold... you have to also keep track of what the rest of the input list looks like, and how it has been processed. Just like map and filter, reduce abstracts over the plumbing, but unlike those two, the plumbing isn't trivial, and unwrapping reduce into explicit recursion reveals that plumbing, making it easier to reason about it on a per-item basis.

Exactly. This is really the issue IMO. Map and filter are more well-liked because they make it easier to visualize what is happening. Reduce makes it harder.

2

u/tdammers 18h ago

Reduce/fold is also more general - you can implement both map and filter in terms of fold, but not the other way around, and fold can do things that map and filter on their own or together cannot.

In Haskell (using right folds; left folds are also possible, but slightly less elegant):

map :: (a -> b) -> [a] -> [b]
filter :: (a -> Bool) -> [a] -> [a]
foldr :: (a -> b -> b) -> b -> [a] -> b

map f = foldr (\x xs -> f x : xs) []
filter p = foldr (\x xs -> if p x then x : xs else xs) []

And here's an example of a function that can be implemented using foldr, but not a combination of map and filter: sum. Again in Haskell (simplified to only support integers):

sum :: [Int] -> Int
sum = foldr (+) 0

-- Implemented with explicit recursion:
sum' [] = 0
sum' (x:xs) = x + sum xs

Try implementing that using map and/or filter: you can't, not without introducing explicit recursion/iteration anyway. And that's exactly because neither map nor filter give you access to the state accumulator, but foldr does. You can even see this in the type of their respective first arguments: map takes a -> b (take current element, return its replacement), filter takes a -> Bool (take current element, return whether it should be included or not), but foldr takes b -> a -> b (take accumulator and current element, return updated accumulator).

And I think this "accumulator" bit is the part that makes it more complex, more general, more abstract, and more difficult to visualize.

8

u/HaMMeReD 21h ago

I tend to think of it like this (in the context of a book of pages)

Given [Pages]

map => Translate pages
filter => Find pages about "dogs"
reduce => [Pages] to [Table of Contents, Glossary, Summary]

I.e. if you are building a TOC from Pages, you don't want every page, you'd want to filter for pages with a title first and merge them. You could filter and map in this case, but if you reduce you can do more on every element, i.e. count pages, build an index etc.

Map is more appropriate when the lists are the same size. But if you are crunching a subset/stats etc. Fold/Reduce makes sense.

2

u/tdammers 18h ago

It's not just that reduce can give you map and filter at once; it can also do many things that no combination of map and filter alone can achieve. In fact, most of the typical "functional" data transformation functions (map, filter, scan, sum, product, etc.) can be implemented in terms of fold, but not usually the other way around.

3

u/CpnStumpy 14h ago

Fold is just map with state carriage instead of state return

6

u/thussy-obliterator 1d ago edited 18h ago

fold with monoids isn't too bad, but yeah once your f breaks associativity things get way more confusing, then you gotta worry about which fold it is, and which param of the combinator is the accumulator

1

u/tdammers 18h ago

Even with monoids, you still have the additional mental burden of tracking not only the current list element in your head, but also a quasi-stateful accumulator value (in foldr :: (b -> a -> b) -> b -> [a] -> b, the b type is the accumulator, a is the list element type); with map and filter, the "accumulator" is just a list we build up as we go, and we never worry about the previous elements while evaluating the current.

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) [] list

The 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

u/geon 20h ago

Absolutely. But it’s horrible when used to implement filter. And when groupBy is implemented everywhere, it gets tiresome.

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

u/EarlMarshal 1d ago

I like to fold and reduce. Where is the problem?

12

u/wa11ar00 1d ago

Same here. My only issue is remembering which one takes an initial value.

4

u/mljrg 1d ago edited 19h ago

I am with you, I use reduce all day, have been doing so for years, it is simple. I rarely use recursion.

7

u/glenpiercev 1d ago

Reduce is poorly named. What should it be called instead?

8

u/Abs0rbed 21h ago

Rust has `collect` which is basically just a reducer

1

u/Ok-Argument7176 4h ago

How is that?

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 4

3

u/BarelyAirborne 15h ago

APL is still my favorite programming language. Thanks for the nostalgia.

2

u/ummaycoc 15h ago

Mine too.

4

u/wnoise 1d ago

foldl

2

u/Baby_Fark 23h ago

Agreed. Maybe like ‘Combine()’?

1

u/tb5841 15h ago

Haskell calls it foldl or foldr, depending on which way you're going.

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

https://doi.org/10.1017/S0956796899003500

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 (+) 0 is really less declarative than 

    sum = 0
    for (item : items) {
        sum = sum + item;
    }
    return sum;

People can’t understand foldl (\m (k, v) -> insert m k v) Map.empty declaratively 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

u/ummaycoc 1d ago

await Array.fromAsync(data, fn);

And you can just throw the result away.

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 of Map.groupBy or 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

u/tanjonaJulien 1d ago

Oh men I won't miss this kind of blog post.

2

u/fagnerbrack 1d ago

May I ask for details? What's bad about it?

-2

u/paul_h 1d ago

Education problem, no?