简体   繁体   English

Haskell将元组列表映射到元组列表

[英]Haskell map list of tuples to list of tuples

I'm trying to map a list of tuples into a different list of tuples with no luck. 我试图将一个元组列表映射到另一个没有运气的元组列表中。

Example input: 输入示例:

a = [("eo","th"),("or","he")]

Example output: 输出示例:

[('e','t'),('o','h'),('o','h'),('r','e')]

I have tried: 我努力了:

map (\(a,b) -> (a!!0,b!!0):(a!!1,b!!1):[]) a

but it produces: 但它产生:

[[('e','t'),('o','h')],[('o','h'),('r','e')]]

You have to use concat on your result or use concatMap instead of map . 您必须在结果上使用concat或使用concatMap而不是map After all, you return lists in your map and therefore get a list of lists. 毕竟,您可以在地图中返回列表,因此可以获得列表列表。


Let's give your function a name and a type: 让我们给函数命名和类型:

magic :: [([Char], [Char])] -> [(Char, Char)]

Now, we can think of this as a two-step process: from every pair in the original list we're going to get a list: 现在,我们可以将其视为一个两步过程:从原始列表中的每一对中,我们将获得一个列表:

magicPair :: ([Char], [Char]) -> [(Char, Char)]
magicPair (a,b) = zip a b

Now we need to map magicPair over all elements in your original list and concatenate the result: 现在,我们需要将magicPair映射到原始列表中的所有元素上,并将结果连接起来:

magic xs = concat (map magicPair xs)

The combination concat . map f 组合concat . map f concat . map f is so common that there is a function called concatMap for this: concat . map f非常普遍,因此有一个名为concatMap的函数:

magic xs = concatMap magicPair xs

And using a function f on a pair instead of two arguments is also common, so magicPair = uncurry zip : 在一对而不是两个参数上使用函数f也很常见,因此magicPair = uncurry zip

magic xs = concatMap (uncurry zip) xs

We can now remove xs on both sides to end up with the final variant of magic : 现在,我们可以在两边都删除xs ,以得到magic的最终变体:

magic = concatMap (uncurry zip)

这是给您输出的快速方法

simplify = (>>= uncurry zip)

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

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