这样的事情是否已经存在,或者我应该将其打包为Hackage(我发现它对收集错误很有用):
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
值得注意的是Applicative
的{{1}}和Monad
实例与此非常相似,但对于产品类型,它可以收集“警告”。
如果我把它打包成Hackage,我可能会添加更多实例,但如果有人已经这样做了,我不想重新发明轮子。