r/coding • • 6d ago

Anecdotally, programmers dislike "reduce"

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

75 comments sorted by

4

u/andarmanik 5d ago

All reduce is a helper to do the following
{
let accum = init()
for (const el of list)
accum next(accum, el)
return accum
}

4

u/fagnerbrack 5d ago

Except it can run in native compiled code not JIT

1

u/andarmanik 5d 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.

4

u/fagnerbrack 5d 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

96

u/tdammers 6d 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.

35

u/Halleys_Vomit 5d 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.

6

u/tdammers 5d 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.

2

u/funkdefied 3d ago

Paraphrasing for the smooth brained devs that couldn’t understand (I am one of those smooth brainers):

“map” and “filter” are both “reduce” where the accumulator is, itself, a collection.

8

u/HaMMeReD 5d 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.

4

u/tdammers 5d 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.

4

u/CpnStumpy 5d ago

Fold is just map with state carriage instead of state return

1

u/Embarrassed-Rise-685 3d ago

These are all list or vector functions where the mapping is from a domain to the same codomain + plus some bijective or injective implication. An endofunctor in the language of the deranged I believe. Now take that same domain but have the codomain be of a lower cardinality. Vector to scalar. Matrix to vector. Finding the singular values of a matrix or the normal equations are examples of reduce because it makes sense that these results are the same in a sense. Reduce however doesn’t promise a way back after. Singular value decomposition is a type of reversible reduce but the norm isn’t.

8

u/thussy-obliterator 5d ago edited 5d 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 5d 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.

21

u/PHLAK 5d 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.

4

u/geon 5d ago

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

4

u/HolyInlandEmpire 5d 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.

1

u/quisido 3d ago

If I need to reduce an array

0

u/No-Replacement-2631 3d ago

It's absurd to reduce that much.

18

u/thequux 5d 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.

1

u/kilkil 3d ago

I think this is a very compelling explanation. thanks for the insights!

30

u/EarlMarshal 5d ago

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

13

u/wa11ar00 5d ago

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

5

u/mljrg 5d ago edited 5d ago

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

11

u/glenpiercev 5d ago

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

11

u/Abs0rbed 5d ago

Rust has `collect` which is basically just a reducer

1

u/Ok-Argument7176 4d ago

How is that?

1

u/funkdefied 3d ago

Rust’s collect returns a collection, not a single value like reduce. Very different in terms of approachability imo. 

1

u/Abs0rbed 3d ago

The collection is the accumulator returned from the reduce operation on the iterator

1

u/AlxandrHeintz 3d ago

It doesn't actually. It returns a FromIterator - which may (and typically is) be a collection. But you can collect into anything that supports it. For instance, if you have an iterator of () you can collect that into just ().

1

u/kilkil 3d ago

no, rust's equivalent to reduce are Iterator::reduce() and Iterator::fold() (as well as a few other variants).

I guess you could argue collect() does something similar, but it's a lot more specialized. you can't "collect" a Vec into a sum, for example.

1

u/AlxandrHeintz 3d ago

You can actually. If you make a struct Sum(usize) and implement FromIterator<usize>, you could do let sum: Sum = my_iter.collect();.

Edit

I'm not saying this is a good idea btw, just that it's possible.

1

u/Abs0rbed 3d ago

It wasn’t a perfect example, I just meant that I often think about reduce as something that “collects” a stream of values rather than “fold”. I just think collect is a more intuitive word for it

1

u/kilkil 2d ago

that's a fair point. "fold" and "reduce" are a lot more abstract (personally I always picture "reduce" in the chemistry sense. like the array/vec is literally getting boiled down to some value).

6

u/ummaycoc 5d 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

4

u/BarelyAirborne 5d ago

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

2

u/ummaycoc 5d ago

Mine too.

3

u/Baby_Fark 5d ago

Agreed. Maybe like ‘Combine()’?

3

u/lookmeat 4d ago

aggregate, which takes an aggregator function and an aggregate (which represents the initial state). It feels, IMHO, more intuitive.

And for unfold I think that build or construct where it takes a function that knows how to build a piece based on some blueprint by splitting it into smaller blueprints. So it works like a parser, but also like your standard builder if you think of the "fluent API" as assembling the blueprint object.

5

u/wnoise 5d ago

foldl

1

u/tb5841 5d ago

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

1

u/tumes 4d 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.

1

u/cdsmith 4d ago

Reduce is named just fine for an associative fold. For non-associative folds, the concept is general enough to not have a good descriptive name, so you can settle on whatever abstract name you like.

1

u/Stanian 4d ago

"aggregate"?

1

u/KontoOficjalneMR 3d ago

What should it be called instead?

accumulate

1

u/kilkil 3d ago

well it kind of "folds" an array in on itself, so maybe it should be called fold... oh wait

1

u/Alpheus2 2d ago

Collect, fold, project. Pick two

4

u/Silent_Marsupial117 5d ago

But reduce/fold are (more?) important:

A tutorial on the universality and expressiveness of fold

Graham Hutton

https://doi.org/10.1017/S0956796899003500

3

u/LemonAncient1950 5d 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);
}

3

u/ummaycoc 5d ago

await Array.fromAsync(data, fn);

And you can just throw the result away.

1

u/kilkil 3d ago

would be better to do Promise.all right?

2

u/LemonAncient1950 2d ago

Depends on the situation. Promise.all waits on all of the promises concurrently rather than sequentially. Generally Promise.all is preferred, but it can bite you if the async operation does some IO like writing to fs/network/etc. If you have an array of thousands of objects and you want to write each one to a file, you could hit ulimit issues trying to write them all at once.

In my experience, you end up needing a mechanism to process data with a max concurrency set (e.g. save 1000 files but only have 10 save operations happening at any given moment) which ends up not being covered exactly by either approach. I'd bet there's a standardized way to do it or one on the way, but I've always done it like this:

async function maxConcurrency<T, R>(
  data: T[],
  fn: (value: T) => Promise<R>,
  max = 10
): Promise<R[]> {
    const remaining = [...data];
    const results: R[] = []

    await Promise.all(Array.from({length: max}).map(async () => {
        while(remaining.length > 0) {
            results.push(await fn(remaining.shift()!))
        }
    }))

    return results;
}

1

u/kilkil 2d ago

hmm yeah I see what you mean.

honestly the standard library really should have something for this IMO

7

u/josephjnk 6d 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 6d 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 5d 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 5d 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/NudeSamoan 5d 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/rafark 3d ago

Give it a try. I’d been avoiding it for years but lately I’ve been using it a lot and it’s quite useful, nicer than writing a loop

1

u/repaj 4d 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.

1

u/kilkil 3d ago edited 3d ago

I used to be somewhat confused by reduce as well, but the example that really cleared it up for me was this:

from operator import add
from functools import reduce

vals = [3, 1, 2, .., 420]

total = reduce(add, vals)

it basically just means "add repeatedly".

and now, after some practice using it (mostly in Rust, using Iterator::fold()) I do quite like it!

... though I will admit that for loops are still easier to read, especially in languages like Python:

values = [...]

total = 0
for n in values:
    total += n

1

u/NewFuturist 1d ago

My experience is that most of the people who use reduce use it incorrectly (e.g. adding fields to an object) and then get upset when you tell them that they shouldn't be using reduce in that situation. Even when you point them to the MDN section about when not to use it, they still don't believe you.

1

u/Mediocre-Brain9051 5d 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...

2

u/cdsmith 4d ago

This is definitely overstated. I've spoken to plenty of people who are very committed to functional programming, but consider the more exotic recursion schemes like non-associative folds, mapAccums, scans, unfolds, etc. to be better written as explicit recursion. It's a hell of a lot less memorization, and easier to understand what's going on from first principles.

1

u/Mediocre-Brain9051 4d ago

reduce is very far from being exotic.

-9

u/fagnerbrack 6d 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 5d 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.

-2

u/paul_h 5d ago

Education problem, no?

-2

u/tanjonaJulien 5d ago

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

3

u/fagnerbrack 5d ago

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