【问题标题】:Concat for wrapped items haskellConcat 包裹物品 haskell
【发布时间】:2021-03-26 09:33:20
【问题描述】:

我有一个类型为 Either 的项目列表: [Right [(a, b)], Right [(a1, b1)], Right [(a2, b2)]] 我想得到Right [(a,b), (a1, b1), (a2, b2)],可以吗? 我正在使用序列来执行此操作,但我得到: Right [[(a,b)], [(a1, b1)], [(a2, b2)]]。我想知道,是否有像 concat 这样的函数可以去掉这些内括号,使其只是一个元组列表。

【问题讨论】:

  • concat <$> sequence yourlist.

标签: haskell either


【解决方案1】:

您可以使用一个函数,该函数对于 Left 返回具有相同值的 Left,对于 Right 返回 Right,您可以将 concat 函数应用于包装在没错:

concatEither :: Either a [[b]] -> Either a [b]
concatEither (Left l) = Left l
concatEither (Right rs) = Right (concat rs)

那么我们可以这样工作:

<b>concatEither</b> (sequence yourlist)

但这已经存在:Either aFunctor typeclass 的一个实例,它为任意函数实现了这个。

因此,我们可以使用fmap :: (a -&gt; b) -&gt; f a -&gt; f b 或其等效的中缀运算符(&lt;$&gt;) :: (a -&gt; b) -&gt; f a -&gt; f b,因此我们可以使用:

concat <b>&lt;$&gt;</b> sequence yourlist

【讨论】:

    【解决方案2】:

    Ap 新类型为您提供任何ApplicativeMonoid 实例,前提是Applicative 本身由Monoid 参数化, Either x [(a,b)] 就是这种情况。所以我们可以写

    getAp . foldMap Ap :: (Monoid a, Applicative f) => [f a] -> f a
    

    【讨论】:

      猜你喜欢
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多