liveBook · Manning

Monoid

As explained in Learn Haskell by Example

Monoid is a Haskell type class extending Semigroup with a neutral element and operations for combining collections of values.

A Monoid is a Haskell type class for values that can be combined associatively and that have an identity value. It extends Semigroup: `(<>)` combines two values, `mempty` leaves a value unchanged, and `mconcat` combines a list of values. section 7.3.1

Listing 7.9 Class signature for Monoid
class Semigroup a => Monoid a where
  mempty :: a  #1
  mappend :: a -> a -> a  #2
  mconcat :: [a] -> a  #3
  {-# MINIMAL mempty #-}

The class requires a Semigroup instance and supplies the neutral value; `mappend` is equivalent to `(<>)` by default, while `mconcat` combines a list. section 7.3.1

The required laws are `mempty <> a == a` and `a <> mempty == a`. Combination must also be associative, so parentheses can change without changing the result: `a <> (b <> c) == (a <> b) <> c`. The compiler does not verify these laws, and associativity does not mean that operand order may be swapped. section 7.3.1

Lists, strings, and numeric wrappers

Lists use `(++)` for `(<>)` and `[]` for `mempty`, so `[1,2,3] <> mempty <> [4,5,6]` produces `[1,2,3,4,5,6]`. Strings combine the same way. `Int` has no single canonical Monoid operation because both addition and multiplication are associative; `Sum` and `Product` select the intended operation. section 7.3.1

A custom data type can become a Monoid when it already has a meaningful associative append operation and a neutral empty value. For CSV data, `appendCsv` supplies `(<>)`, while a CSV with no header and no columns supplies `mempty`; this makes appending optional input a normal transformation step. section 7.3.1 section 8.4.1

Figure 7.1 Different scenarios when appending two tables of data
figure

Appending CSV tables must account for headers, columns, and missing cells before it can serve as the associative combination operation. section 7.3.1

How Learn Haskell by Example covers it

How deep it goes
Defines Monoid operations and laws, demonstrates built-in instances, and implements a Csv instance without proving laws formally.
Examples
Demonstrates list and String concatenation, `mconcat`, numeric Sum/Product wrappers, and CSV table appending.
What it assumes
Introduces the abstraction alongside CSV modeling and type classes, using familiar list and String concatenation as examples.
What you can do after
Apply it via Haskell type class instances to combine lists, strings, and CSV values using `(<>)`, `mempty`, and `mconcat`.
How it connects
Connects Monoid to Semigroup, type classes, lists, Strings, Sum, Product, and CSV transformation.

Also explained in

Compare how 3 books explain Monoid →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.