像这样的东西是否已经存在或者我应该为 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
和的Monad
实例(,)
与此非常相似,但它是用于收集“警告”的产品类型。
如果我为 Hackage 打包它,我可能会添加更多实例,但如果有人已经这样做了,我不想重新发明轮子。