[英]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
返回具有相同值的Left
, Right
返回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 a
是Functor
类型类的一个实例,它为任意 function 实现了这个。
因此,我们可以使用fmap:: (a -> b) -> fa -> fb
或其等效的中缀运算符(<$>):: (a -> b) -> fa -> fb
,所以我们可以工作和:
concat <$> sequence yourlist
Ap
newtype 为您提供任何Applicative
的Monoid
实例,前提是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.