Does something like this already exist or should I package it up for Hackage (I find it useful for collecting errors):
module EitherSemigroup where
import Prelude hiding (Right, Left)
import Data.Semigroup (Semigroup)
data EitherSemigroup l r = Left l | Right r
instance Functor (EitherSemigroup l) where
fmap f (Right x) = Right (f x)
fmap _ (Left x) = Left x
instance Semigroup l => Applicative (EitherSemigroup l) where
pure = Right
(<*>) (Right f) (Right x) = Right (f x)
(<*>) (Right _) (Left x) = Left x
(<*>) (Left x) (Right _) = Left x
(<*>) (Left x1) (Left x2) = Left (x1 <> x2)
instance Semigroup l => Monad (EitherSemigroup l) where
(>>=) (Right x) f = f x
(>>=) (Left x) _ = Left x
It's worth noting that the Applicative
and Monad
instances for (,)
are very similar to this but for a product type, which does the job for collecting "warnings".
If I do package it up for Hackage I'd probably add more instances but if someone has already done this I don't want to reinvent the wheel.