【问题标题】:Is there a standard name or implementation of the "purely applicative Either"?是否有“纯粹适用的 Either”的标准名称或实现?
【发布时间】:2014-03-08 02:51:44
【问题描述】:

我经常发现我称之为“纯应用Either”的东西,即EitherApplicative 实例可用,只要我们不实现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,因为它提供了比EitherMonad 实例更强大的“错误汇总”概念。为此,我发现自己一遍又一遍地实施它。

某处有标准实例吗?有没有标准的名字?

【问题讨论】:

  • 如果你向我的errors 库提交补丁,我会接受。
  • 我可能最终会这样做。不过,我真的觉得这属于某种更通用的applicatives 包以及纯粹的应用产品。
  • 这似乎是相同的,semigroups 是一个很好的地方。我一直在内部称它为Collect

标签: haskell applicative either


【解决方案1】:

这看起来与 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)

【讨论】:

  • 同一个!我喜欢这仅取决于Semigroup,因为这当然是绝对必要的。
猜你喜欢
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 2014-10-04
  • 1970-01-01
  • 2017-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多