Haskell Monoids

Priyanka Mondal
2 min readApr 25, 2020

First, let us see what algebraic structures are. An algebraic structure comprises of three parts: a set of elements, a set of operations on the elements with finite arity, and a set of identity elements. Monoid is an algebraic structure with an associative binary operation and an identity element. Examples of monoids would be (N,+,1), (Z,*,0), ([N],++,[]) etc.

class Monoid a where  mempty :: a
mappend :: a -> a -> a
mconcat :: [a] -> a
mconcat = foldr mappend mempty

The Haskell implementation of Monoid is shown above. Unlike functors and applicatives it takes a base type,a, instead of a type constructor as a parameter. mempty is the identity element, and mappend is the associative binary function. mconcat can be ignored for the moment, as it comes with a default implementation and is not implemented for every monoid instance. If A is the set of elements of type a, then the monoid is (A,mappend,mempty).

mappend sounds like append but it can be any binary operation.

Lists can be instance of Monoid.

instance Monoid [a] where
mempty = []
mappend = (++)

The identity element is the empty list and the binary function is the append function which takes two lists of type [a] and returns a list of type [a].

Ordering type is also an instance of Monoid. Ordering type can have three values, EQ, LT, GT.

instance Monoid Ordering where
mempty = EQ
mappend LT _ = LT
mappend GT _ = GT
mappend EQ x = x

The result of mappend depends on the value of the first parameter. GT is greater than everything, LT is less that everything, and EQ of the second parameter is the second parameter itself.

Maybe is also an instance of Monoid. ({Maybe a}, mappend, Nothing)

instance Monoid a => Monoid (Maybe a) where
mempty = Nothing
mappend Nothing m = m
mappend m Nothing = m
mappend (Just m1) (Just m2) = Just (mappend m1 m2)

To test on ghci

ghci> mappend (Just "mom")  (Just "dad" )
Just "momdad"

--

--