“纯适用的任何一种"是否有标准名称或实现? [英] Is there a standard name or implementation of the "purely applicative Either"?
问题描述
我经常找到我所谓的纯粹适用的Either
"的用法,即只要我们也没有实现Monad
实例,就可以使用Either
和Applicative
实例.
I frequently find use for what I call the "purely applicative Either
", i.e. Either
with the Applicative
instance available so long as we don't implement a Monad
instance as well.
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
实例更强大的错误汇总"概念.为此,我发现自己要一遍又一遍地实现它.
It's a really useful Applicative
as it provides a more powerful notion of "summarization of error" than Either
's Monad
instance can do. To that end, I find myself implementing it over-and-over again.
某处有一个标准实例吗?甚至有一个标准名称吗?
Is there a standard instance somewhere? Is there even a standard name?
推荐答案
这与validation
包中的AccValidation类型非常相似:
This looks pretty similar to the AccValidation type in the validation
package: 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)
这篇关于“纯适用的任何一种"是否有标准名称或实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!