r/coding • • 16d ago

Anecdotally, programmers dislike "reduce"

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

77 comments sorted by

View all comments

Show parent comment

35

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