Monoids

mempty and mappend

A monoid is a type with an associative binary operation and an identity element. Those two facts are enough to fold a whole list without knowing anything about the values:

-- the standard library defines it as: -- class Semigroup a => Monoid a where -- mempty :: a -- mappend :: a -> a -> a mempty :: [Int] -- [] [1,2] <> [3] -- [1,2,3]

<> is the modern name for mappend, and it belongs to Semigroup. The monoid adds the empty value that the semigroup lacks.

The common instances

Four instances appear in everyday code. Each one answers the same question: what is the empty value, and how do two values combine?

-- lists concatenate, empty is [] [1] <> [2] -- [1,2] -- strings are lists of characters "ab" <> "cd" -- "abcd" -- Maybe combines the values when both are present (Just "a" <> Just "b") :: Maybe String -- Just "ab" (Nothing <> Just "b") :: Maybe String -- Just "b"

The Maybe instance is the one that surprises people: when both sides are Just it combines the values, and a Nothing disappears. Use it to sum the successes in a list without writing a case:

Sum, Product, Any, All

Numbers have two reasonable monoids, so the library wraps them in newtypes instead of picking one. This is the payoff of lesson 27:

import Data.Monoid (Sum(..), Product(..), Any(..), All(..)) getSum (Sum 2 <> Sum 3) -- 5 getProduct (Product 2 <> Product 3) -- 6 getAny (Any False <> Any True) -- True getAll (All True <> All False) -- False

Any is logical or with False as the identity, and All is logical and with True. Both give a fold over a list of booleans for free.

Combining records

The most useful application is merging partial results. Write the instance once and a fold over a list of records does the rest:

data Stats = Stats { count :: Sum Int , total :: Sum Int } deriving (Show) instance Semigroup Stats where a <> b = Stats (count a <> count b) (total a <> total b) instance Monoid Stats where mempty = Stats mempty mempty

Now foldMap over a list of records sums every field at once, and a new field only means one more line in the instance.

The code on this page was run with GHC 9.10.3 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev