Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consideration to add Universe and Finite instances for These a b #160

Open
subttle opened this issue May 9, 2021 · 0 comments
Open

Consideration to add Universe and Finite instances for These a b #160

subttle opened this issue May 9, 2021 · 0 comments

Comments

@subttle
Copy link

subttle commented May 9, 2021

Hello!
Thank you all again for all your work on this excellent package.
I wrote instances for universe's Universe and Finite classes for the These a b type.
If you are interested in having support for these instances included then please let me know, I would gladly make a PR.

The code is pretty straight forward.

import Control.Applicative  (liftA2)
import Data.Tagged          (Tagged (..), retag)
import Data.Universe        (Finite (..), Universe (..))
import Numeric.Natural      (Natural)

toThese :: Either (Either a b) (a, b) -> These a b
toThese = either (either This That) (uncurry These)

instance (Universe a, Universe b) => Universe (These a b) where
  universe :: [These a b]
  universe = fmap toThese universe

instance (Finite a, Finite b) => Finite (These a b) where
  -- a + b + ab
  cardinality :: Tagged (These a b) Natural
  cardinality = liftA2 (\a b -> a + b + a * b) (retag (cardinality :: Tagged a Natural))
                                               (retag (cardinality :: Tagged b Natural))
  universeF :: [These a b]
  universeF = fmap toThese universeF

If you are not comfortable with the name toThese then it can simply be inlined to avoid giving it a name, or I am open to suggestions for a different name :)

Here are some example usages in GHCi:

λ> mapM_ print (universeF @ (These () Bool))
This ()
That False
That True
These () False
These () True
λ> cardinality @ (These () Bool)
Tagged 5

If you are not interested then I won't take offense and please close the ticket; any feedback is certainly welcomed. Thank you for your time and consideration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant