3 ms·
`foldMap` and `fold` in Haskell only require Monoid because there are many common cases where you're folding over a monoidal type; they are simply conveniences.
by aseipp 8y ago
`foldMap` and `fold` in Haskell only require Monoid because there are many common cases where you're folding over a monoidal type; they are simply conveniences. The alternative is to always define things in terms of `foldr` which is more "fundamental" (since its type represents a church encoding of the underlying type) which, as you note, does not require a Monoid.
All that said, as another commentor noted, most of the time people actually want to talk about Monoids and not Semigroups, because identities are extremely convenient for accumulating results, and all Semigroups can be upgraded to Monoids (in Haskell this is as easy as changing type `a` to `Maybe a` for any Semigroup `a`). Arrays or counters are easy examples. You can of course use specifically designated "seed" values and argue Monoids aren't necessary but you're probably going to start adding code that does stuff like "if value == seed then ..." -- and at that point you probably are dealing with a Monoid, whether you recognize it or not. Again, the easiest example would be in Haskell, where you say "I can combine these things of type `a`. But I can't always produce a result, so instead I want `Maybe a`, and occasionally I'll produce Nothing instead, and then..." -- and that's exactly the Monoid you get by upgrading any Semigroup.
So you are correct that fold has no a priori requirement for a Monoid, but in practice you probably will want monoidal composition semantics a lot of the time.