TExcelTAD
Home › Haskell › Haskell Semigroup & Monoid

Haskell Semigroup & Monoid

Many operations share one simple shape: take two things of the same type and combine them into one. Joining strings, adding numbers, merging maps, taking a maximum. Haskell names that shape with two small type classes.

haskell
class Semigroup a where
  (<>) :: a -> a -> a           -- combine; must be associative

class Semigroup a => Monoid a where
  mempty :: a                   -- the "empty" element: x <> mempty == x

A Semigroup has an associative combining operation <>. A Monoid is a semigroup that also has a neutral element mempty.

Built-in instances

haskell · try it yourself
import qualified Data.Map as Map

main :: IO ()
main = do
  print ("Hello, " <> "monoid")                 -- strings and lists: concatenation
  print ([1, 2] <> [3] <> [])
  print (mempty :: String)
  print (Just [1] <> Nothing <> Just [2, 3])   -- Maybe: combines the contents
  print (Map.fromList [(1, "a")] <> Map.fromList [(1, "z"), (2, "b")])  -- left-biased union
  print (mconcat ["con", "cat", "en", "ate"])   -- combine a whole list
  print (LT <> GT, EQ <> GT)                    -- Ordering: the first non-EQ wins
"Hello, monoid"
[1,2,3]
""
Just [1,2,3]
fromList [(1,"a"),(2,"b")]
"concatenate"
(LT,GT)

mconcat folds a list with <>, starting from mempty. For lists it is the same as concat.

Numbers: which operation?

Numbers can be combined by addition (neutral element 0) or multiplication (neutral element 1), and both are valid monoids. Since a type can have only one instance of a class, Data.Monoid and Data.Semigroup provide newtype wrappers that pick the operation:

haskell · try it yourself
import Data.Monoid (Sum (..), Product (..), Any (..), All (..), First (..))
import Data.Semigroup (Max (..), Min (..))

main :: IO ()
main = do
  let xs = [3, 1, 4, 1, 5] :: [Int]
  print (getSum (foldMap Sum xs))
  print (getProduct (foldMap Product xs))
  print (getMax (foldMap Max xs), getMin (foldMap Min xs))
  print (getAny (foldMap (Any . even) xs), getAll (foldMap (All . (> 0)) xs))
  print (getFirst (foldMap (First . Just) "abc"))
  print (Sum 2 <> Sum 3, Product 2 <> Product 3)
14
60
(5,1)
(True,True)
Just 'a'
(Sum {getSum = 5},Product {getProduct = 6})
Wrapper <> mempty
Sum a + 0
Product a * 1
Max a, Min a max, min (semigroup only, unless Bounded)
Any, All ||, && False, True
First a, Last a first / last Just Nothing

foldMap f maps every element to a monoid with f and combines them all. It is one of the most useful functions in the library.

Combining several statistics at once

Tuples of monoids are monoids too, component by component. So you can compute several summaries in one pass over the data:

haskell · try it yourself
import Data.Monoid (Sum (..))
import Data.Semigroup (Max (..), Min (..))

summary :: [Int] -> (Sum Int, Sum Int, Max Int, Min Int)
summary = foldMap (\x -> (Sum 1, Sum x, Max x, Min x))

main :: IO ()
main = do
  let readings = [18, 22, 19, 25, 21]
      (Sum n, Sum total, Max hi, Min lo) = summary readings
  print (n, total, hi, lo)
  print (fromIntegral total / fromIntegral n :: Double)
(5,105,25,18)
21.0

Your own Semigroup and Monoid

Define <> (and mempty for a monoid). Here a shopping cart merges quantities and keeps track of the number of updates:

haskell · try it yourself
import qualified Data.Map.Strict as Map

data Cart = Cart {items :: Map.Map String Int, updates :: Int}
  deriving Show

instance Semigroup Cart where
  Cart a n <> Cart b m = Cart (Map.unionWith (+) a b) (n + m)

instance Monoid Cart where
  mempty = Cart Map.empty 0

add :: String -> Int -> Cart
add item qty = Cart (Map.singleton item qty) 1

main :: IO ()
main = do
  let morning = add "apple" 3 <> add "bread" 1
      evening = add "apple" 2 <> add "milk" 1
  print (morning <> evening)
  print (mconcat [add "tea" 1, add "tea" 1, mempty])
  print (mempty :: Cart)
Cart {items = fromList [("apple",5),("bread",1),("milk",1)], updates = 4}
Cart {items = fromList [("tea",2)], updates = 2}
Cart {items = fromList [], updates = 0}

Why associativity matters

Associativity, (a <> b) <> c == a <> (b <> c), means you can group the combinations any way you like. That is what lets a library split a big mconcat across CPU cores, or combine partial results from different servers, and still get the same answer. The neutral element means an empty input has a sensible result.

Sorting by several keys with Ordering

Ordering is a monoid where the first non-EQ result wins. Combined with comparing, it gives multi-key sorting in one line:

haskell · try it yourself
import Data.List (sortBy)
import Data.Ord (comparing, Down (..))

data Runner = Runner {runner :: String, country :: String, minutes :: Int}

main :: IO ()
main = do
  let runners =
        [ Runner "Ines" "PT" 182, Runner "Tom" "UK" 175
        , Runner "Rui" "PT" 175, Runner "Amy" "UK" 190 ]
      order = comparing country <> comparing (Down . minutes) <> comparing runner
  mapM_ (\r -> putStrLn (country r ++ " " ++ show (minutes r) ++ " " ++ runner r)) (sortBy order runners)
PT 182 Ines
PT 175 Rui
UK 190 Amy
UK 175 Tom

This works because functions returning a monoid are monoids too: (f <> g) x = f x <> g x.

Test yourself

What is mempty for the String monoid?

  1. " "
  2. ""
  3. Nothing
  4. 0

What is getSum (foldMap Sum [1, 2, 3, 4])?

  1. 4
  2. 10
  3. 24
  4. [1,2,3,4]

Why does Haskell need wrappers like Sum and Product?

  1. Numbers are not monoids
  2. A type can have only one instance of a class, but numbers have two natural monoids
  3. For performance
  4. To allow negative numbers