[ library, mit, unclassified ] [ Propose Tags ]

A Difference Monoid, to add subtraction to arbitrary monoids. Please see the README on Github at https://github.com/oisdk/difference-monoid#readme

[Skip to Readme]
Versions [faq]
Change log ChangeLog.md
Dependencies adjunctions, base (>=4.7 && <5), comonad, deepseq, distributive, groups, semigroupoids [details]
License MIT
Copyright 2018 Donnacha Oisín Kidney
Author Donnacha Oisín Kidney
Maintainer mail@doisinkidney.com
Home page https://github.com/oisdk/difference-monoid#readme
Bug tracker https://github.com/oisdk/difference-monoid/issues
Source repo head: git clone https://github.com/oisdk/difference-monoid
Uploaded by oisdk at Sun May 20 00:03:53 UTC 2018
Distributions NixOS:
Downloads 128 total (19 in the last 30 days)
Rating (no votes yet) [estimated by rule of succession]
Your Rating
  • λ
  • λ
  • λ
Status Hackage Matrix CI
Docs available [build log]
Last success reported on 2018-05-20 [all 1 reports]




Maintainer's Corner

For package maintainers and hackage trustees

Readme for difference-monoid-

[back to package description]


This package provides the Difference Monoid, which adds subtraction to arbitrary monoids.

This has a number of uses:

  • Diff (Product a) will give you a type similar to Data.Ratio. Here, the "subtraction" operation is division. For example:

    >>> (1 :-: 2) <> (3 :-: 4) :: Diff (Product Int)
    Product {getProduct = 3} :-: Product {getProduct = 8}
  • In a similar vein, Diff (Sum a) will add subtraction to a numeric type:

    >>> runDiff (-) (diff 2 <> diff 3 <> invert (diff 4)) :: Sum Natural
    Sum {getSum = 1}

    This will let you work with nonnegative types, where you need some form of subtraction (for, e.g., differences, hence the name), and you only want to check for underflow once.

  • Using the above example, in particular, we get a monoid for averages:

    >>> import Data.Function (on)
    >>> let avg = runDiff ((%) `on` getProduct.getSum) . foldMap (fmap Sum . diff . Product)
    >>> avg [1,4,3,2,5]
    3 % 1

The Monoid and Semigroup laws hold in a pretty straightforward way, provided the underlying type also follows those laws.

For the Group laws, the underlying type must be a cancellative semigroup.

A cancellative semigroup is one where

  • a <> b = a <> c implies b = c
  • b <> a = c <> a implies b = c

If this does not hold, than the equivalence only holds modulo the the addition of some constant

Most common semigroups are cancellative, however notable exceptions include the cross product of vectors, matrix multiplication, and sets:

fromList [1] <> fromList [1,2] = fromList [1] <> fromList [2]`

This type is known formally as the Grothendieck group.

The package also provides the Parity monad and comonad, which is left-adjunct to the difference monoid.