https://github.com/chris-martin/multi-instance
Multiple typeclass instances, selected by explicit application of a phantom type parameter
https://github.com/chris-martin/multi-instance
haskell-library monoid phantom-types semigroup
Last synced: 8 months ago
JSON representation
Multiple typeclass instances, selected by explicit application of a phantom type parameter
- Host: GitHub
- URL: https://github.com/chris-martin/multi-instance
- Owner: chris-martin
- Created: 2017-09-21T04:53:36.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2022-03-15T20:12:50.000Z (over 3 years ago)
- Last Synced: 2025-01-31T09:22:39.744Z (8 months ago)
- Topics: haskell-library, monoid, phantom-types, semigroup
- Language: Haskell
- Homepage: https://hackage.haskell.org/package/multi-instance
- Size: 26.4 KB
- Stars: 3
- Watchers: 4
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# multi-instance
[](https://travis-ci.org/chris-martin/multi-instance)
Alternative versions of common typeclasses, augmented with a phantom type
parameter `x`. The purpose of this is to deal with the case where a type has
more than one candidate instance for the original, unaugmented class.## Example: Integer sum and product
The canonical example of this predicament is selecting the monoid instance for a
type which forms a ring (and thus has at least two strong candidates for
selection as *the* monoid), such as `Integer`. This therefore gives rise to the
`Sum` and `Product` newtype wrappers, corresponding to the additive and
multiplicative monoids respectively.The traditional `fold`-based summation of a list of integers looks like this:
```haskell
>>> import Data.Foldable (fold)
>>> import Data.Monoid (Sum (..))
>>> getSum (fold [Sum 2, Sum 3, Sum 5]) :: Integer
10
```By replacing `fold` with `multi'fold`, whose constraint is `MultiMonoid` rather
than `Data.Monoid.Monoid`, we can write the same thing without the newtype
wrapper:```haskell
>>> :set -XFlexibleContexts -XTypeApplications
>>> multi'fold @Addition [2, 3, 5] :: Integer
10
```