Haskell Semigroup and Monoid: When Each One Fits
A student brought me a function last term that merged three configuration records into one. It folded over a list of records with a hand-written starting value, and it worked until someone called it with an empty list and got back a record...

A student brought me a function last term that merged three configuration records into one. It folded over a list of records with a hand-written starting value, and it worked until someone called it with an empty list and got back a record full of zeros, which silently overrode the defaults that had already been read from disk. The fold was correct. The starting value was a guess, typed once and never questioned again.
That bug is the reason Haskell has two classes here instead of one. Semigroup says how to combine two values. Monoid says what the neutral value is, and whether one exists at all. Keeping them separate is not tidiness for its own sake; it is the difference between a compiler that can tell you the empty case is undefined and a compiler that lets you invent an answer.
What Semigroup actually promises
A Semigroup instance gives you one operator, <>, with the type a -> a -> a. The only law is associativity: (x <> y) <> z must equal x <> (y <> z). That is the whole contract. It does not promise commutativity, and the instances people meet first make that obvious.
ghci> "fish" <> "cake"
"fishcake"
ghci> [1,2] <> [3]
[1,2,3]
ghci> Just [1] <> Just [2]
Just [1,2]
ghci> Nothing <> Just [2]
Just [2]
String concatenation is associative and clearly not commutative, which is the point I make in class before anyone writes a law-breaking instance. The Maybe instance is worth a second look: it requires the inner type to be a Semigroup, and it treats Nothing as something to skip over. That skipping behaviour is where the identity element starts to appear on its own.
Associativity is not decoration. It is what lets a library split your combining work across a tree, or a parallel fold, and still get the same answer. If your instance breaks it, nothing fails loudly. You get results that depend on how the data happened to be chunked, which is the worst category of bug to chase.
Why mempty needs its own class
Monoid adds exactly one thing: mempty, a value that satisfies mempty <> x == x and x <> mempty == x. Since base 4.11 the class is defined as class Semigroup a => Monoid a, and mappend is a legacy alias for <> that you should not write in new code.
The split matters because useful Semigroups exist that have no identity. Data.List.NonEmpty.NonEmpty is one: you can append two non-empty lists, but there is no non-empty list that acts as a neutral element. Data.Semigroup.Min and Max over Int are the same story. There is no Int that is smaller than every other Int while also leaving its partner unchanged, unless you widen the type to admit infinity, which is what Data.Semigroup.Min deliberately refuses to do.
So when you write a function with a Monoid a constraint, you are asserting that the empty case has a correct answer. When you write Semigroup a, you are asserting it does not, and the type system will stop callers from passing an empty container. My student's merge function wanted the second signature. Written as mergeConfigs :: NonEmpty Config -> Config, the bug would not have compiled.
The newtypes that pick an operation
Numbers are the awkward case. Int has two perfectly good monoids, addition with zero and multiplication with one, so base refuses to pick and provides neither instance directly. Instead you wrap the value in a newtype that names the operation you meant. This is the clearest everyday use of the newtype pattern for tagging meaning, and it costs nothing at runtime because the wrapper is erased during compilation.
| Wrapper | Module | Combines by | mempty |
|---|---|---|---|
Sum | Data.Monoid | Addition | Sum 0 |
Product | Data.Monoid | Multiplication | Product 1 |
Any | Data.Monoid | Logical or | Any False |
All | Data.Monoid | Logical and | All True |
First | Data.Monoid | Keeps the leftmost Just | First Nothing |
Min, Max | Data.Semigroup | Smaller, larger | none, Semigroup only |
Endo | Data.Monoid | Function composition | Endo id |
One trap that catches almost everyone: there are two types called First. The one in Data.Monoid wraps a Maybe and keeps the leftmost Just. The one in Data.Semigroup wraps a bare value and keeps the leftmost of anything. Importing both unqualified gives an ambiguity error that reads as though you mistyped a name. I import Data.Monoid qualified in teaching material for this reason alone.
Endo is the one students dismiss and later find indispensable. It turns "apply these transformations in order" into a monoid, so a list of Config -> Config adjustments can be collapsed with appEndo . foldMap Endo rather than a hand-rolled recursion. Note the ordering: Endo f <> Endo g is f . g, so the leftmost function runs last.
The advice to just write a fold is wrong
Experienced developers often tell beginners to skip these classes and write foldr with an explicit operator and starting value, on the grounds that it is more readable and avoids a layer of abstraction. I taught it that way for two semesters and stopped, because the advice quietly moves a decision from the type signature into the function body where nobody reviews it.
Compare the two. A fold with an explicit zero means every call site trusts that whoever wrote the zero got it right, and an incorrect zero produces a plausible wrong answer instead of an error. A foldMap with a wrapper means the zero comes from an instance that was written once, is tested by the library, and is named in the import list where a reader can check it.
The readability claim also does not survive contact with multiple results. Suppose you want the total line count, the maximum file size, and whether any file failed to parse, in a single pass over a few thousand files. With explicit folds that is three traversals or one fold over a triple with a three-part starting value. With monoids it is one foldMap producing a tuple, because tuples are monoids component-wise when their components are:
summarize :: [FileInfo] -> (Sum Int, Max Int, Any)
summarize = foldMap (\f -> (Sum (lines f), Max (bytes f), Any (failed f)))
Tuple instances go up to five components in base, and past three the readability argument flips the other way, so that is roughly where I stop and define a record with a derived instance instead. The comparison of foldr and foldl is still worth reading, because foldMap inherits the same laziness questions underneath.
One thing to try this week
Find a function in your own code with a signature like [Thing] -> Summary that contains a hand-written empty value. Ask what that value means when the list is genuinely empty. If it means "nothing happened", you have a monoid and should name it. If it means "this should not have been called", change the input type to NonEmpty Thing and let the callers deal with it. Both outcomes are improvements, and the second one is the one that finds bugs.
Then write mconcat once by hand to prove to yourself it is just foldr (<>) mempty with an instance-specific override for efficiency. That exercise takes about ten minutes and removes most of the mystique. Readers who want the next step up in abstraction will find that Functor and Applicative solve a related problem for values inside a structure rather than values of the same type.
FAQ
Do I need to write a Semigroup instance before a Monoid instance?
Yes. Since base 4.11, Monoid has Semigroup as a superclass, so GHC will reject a Monoid instance for a type with no Semigroup instance. Define <> first, then define mempty and leave mappend alone.
How do I check my instance is lawful?
QuickCheck with three generated values and an associativity property catches most mistakes in a few seconds. The checkers package on Hackage ships ready-made law batteries for both classes if you prefer not to write the properties yourself.
Why does mconcat exist if foldMap id does the same thing?
Mostly performance. mconcat is a class method, so an instance can supply a faster implementation. Data.Text uses this to size the output buffer once instead of appending repeatedly, which turns a quadratic pattern into a linear one on large inputs.
Is stimes worth knowing about?
Occasionally. stimes n x repeats a value n times under <>, and types like Data.Text override it to be logarithmic rather than linear. I have reached for it perhaps twice in production code, both times for padding.
More in Programming
Programming
Haskell where vs let and Which One to Reach For
A student sent me a function in the third week of last term that worked out a shipping band from a weight in grams and a...
Programming
Haskell Typed Holes for Writing Code With GHC's Help
You know roughly what a function should do, you have written the signature, and then you sit there staring at the right-hand...
Programming
Haskell Functor and Applicative Explained With Real Code
You have a value stuck inside a Maybe, a list, or an IO action, and you keep writing case expressions just to apply one small...