繁体   English   中英

Concat 包裹物品 haskell

[英]Concat for wrapped items haskell

我有一个类型为 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 这样的 function 将摆脱这些内括号,使其只是一个元组列表。

您可以使用 function , Left返回具有相同值的LeftRight返回Right ,您将concat function 应用于包装在右边的值,因此:

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

那么我们可以使用:

concatEither (sequence yourlist)

但这已经存在: Either aFunctor类型类的一个实例,它为任意 function 实现了这个。

因此,我们可以使用fmap:: (a -> b) -> fa -> fb或其等效的中缀运算符(<$>):: (a -> b) -> fa -> fb ,所以我们可以工作和:

concat <$> sequence yourlist

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM