【发布时间】:2014-03-08 02:51:44
【问题描述】:
我经常发现我称之为“纯应用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 实例更强大的“错误汇总”概念。为此,我发现自己一遍又一遍地实施它。
某处有标准实例吗?有没有标准的名字?
【问题讨论】:
-
如果你向我的
errors库提交补丁,我会接受。 -
我可能最终会这样做。不过,我真的觉得这属于某种更通用的
applicatives包以及纯粹的应用产品。 -
这似乎是相同的,semigroups 是一个很好的地方。我一直在内部称它为
Collect。
标签: haskell applicative either