Haskell World logo Haskell WorldWrite code, build worlds
Programming

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 laptop showing a Haskell module with instance declarations beside a notebook with hand-drawn boxes joined by arrows

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.

WrapperModuleCombines bymempty
SumData.MonoidAdditionSum 0
ProductData.MonoidMultiplicationProduct 1
AnyData.MonoidLogical orAny False
AllData.MonoidLogical andAll True
FirstData.MonoidKeeps the leftmost JustFirst Nothing
Min, MaxData.SemigroupSmaller, largernone, Semigroup only
EndoData.MonoidFunction compositionEndo 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.

AS
Adil Sato

Adil Sato teaches programming concepts at a community college and writes online guides for the questions students ask most in the second week of class, not the first. His focus is on making type systems, monads, and functional patterns understandable without reducing them to metaphors that break down the moment you try to use them for real work.

More posts by Adil

More in Programming

01doorganico 084goad 3hot8 4465456 after5internprogram ahandfulofblessings ahmadpc ahomcybersecurity allodialresources annodex antiquesandperiodcollectibles aotc asianworldkashmir beedlectrics bloggertemplatefree bluefeatheragency bodyweightsolution campaign08blog carfixadvisor catstreetcollective cbstvsports cnfanspurchasing committeeof500yearsofdignityandresistance covertopsdjs cs-kaiyuangame cuestacomunicaciontotal cxoutlet dancebetgame deskgearhub destinyvillastay detectmagazine di33 diamondsteelbuildings donmo dyanadropship emarsysfinance emimattl escapechan eskitarih evautoplay everythingweddings-orlando farmzone feedviewerapp foxstudiosscratch gamevui123 gleasongrade greetingsday hacklabasu iw-kaiyun jagoanproperti jilidskripsi joltbusinessfinance juegodepokergratis juegospucca kaeru-festival latestmehndidesigns lestanzediottaviano litemagazines localcommunityhero lustrsazan mariashebets menswheels newwebstechs1 nikkit ootheday oxigenvpn plurfitness prefetial probudgetcarpetcleaning psychicmrsmartin pyaten qvantor rejoignezlogis rexzbot riselayouts ruchin rwxqsgd5 sakaltime shibiaowang shop-bot skrtips spotlesshaven strcoding tetapatrium topselller uneplanteartificielle vipertechcr webtech1223411 wo-kygaming yamaha-mekar yeknava yoybuysheets zenunwa yamaha-mekar jilidskripsi ankertoto ankertoto ankertoto