Derive monoid instances for product types.

Version on this page:
LTS Haskell 17.9:
Stackage Nightly 2021-04-06:
Latest on Hackage:

See all snapshots generic-monoid appears in

BSD-3-Clause licensed by Luke Clifton
Maintained by
This version can be pinned in stack with:generic-monoid-,856

Module documentation for

Depends on 1 package(full list with versions):
Used by 2 packages in lts-15.3(full list with versions):

Generic Monoid (and Semigroup)

This library provides a method of deriving Semigroup and Monoid instances for your large product types. It does this using GHC generics, and can provides a mechanism for using the DerivingVia extension to reduce boilerplate.

It only works if each field of your product type is itself a Semigroup/Monoid.

{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DerivingVia        #-}
{-# LANGUAGE DeriveGeneric      #-}

import GHC.Generics
import Data.Monoid.Generic

data BigProduct = BigProduct
    { theList   :: [Int]
    , theSum    :: Sum Double
    , theString :: String
    } deriving (Generic, Eq)
    deriving Semigroup via GenericSemigroup BigProduct
    deriving Monoid    via GenericMonoid BigProduct

useIt :: Bool
useIt = (mempty <> mempty) == BigProduct [] 0 ""


Revision history for generic-monoid – 2018-12-12

  • Initial release.