我经常发现我称之为“纯粹适用Either
”,即只有Either
实例的Applicative
,只要我们不实现Monad
实例也是。
newtype AEither e a = AEither { unAEither :: Either e a }
deriving Functor
-- technically we only need Semigroup
instance Monoid e => Applicative (AEither e) where
pure a = AEither (pure a)
AEither e1 <*> AEither e2 = AEither (combine e1 e2) where
combine (Right f) (Right a) = Right (f a)
combine (Left m1) (Left m2) = Left (m1 <> m2)
combine (Left m ) _ = Left m
combine _ (Left m ) = Left m
这是一个非常有用的Applicative
,因为它提供了比Either
Monad
实例所能做的更强大的“错误摘要”概念。为此,我发现自己一遍又一遍地实施它。
某处有标准实例吗?是否有标准名称?
答案 0 :(得分:7)
这看起来与validation
包中的AccValidation类型非常相似:http://hackage.haskell.org/package/validation-0.3.1/docs/Data-Validation.html
编辑:
特别是以下实例声明:
instance Semigroup err => Apply (AccValidation err) where
AccFailure e1 <.> AccFailure e2 =
AccFailure (e1 <> e2)
AccFailure e1 <.> AccSuccess _ =
AccFailure e1
AccSuccess _ <.> AccFailure e2 =
AccFailure e2
AccSuccess f <.> AccSuccess a =
AccSuccess (f a)