如何通过列表中的索引从元组中 select 元素?

How to select element from tuple by index in list?

我想 select 列表中的元素,[[1,2],[3,4],[5,6]] 第一个,第二个,第一个和很快。 我想我可以使用 zip 在对前面添加一个计数器并对 select 部分使用模数,现在我的列表如下所示:

let a = [(0,[1,2]),(1,[3,4]),(2,[5,6]),(3,[7,8]),(4,[9,10])]

但是我现在如何select元素呢?

伪代码是

for each tuple in list:
      first part of tuple is the selector, second part is the pair
      if selector mod 2 : choose pair[0] else choose pair[1]

列表 a 的输出应该是:1,4,5,7,9

也许:

> zipWith (!!) [[1,2],[3,4],[5,6],[7,8],[9,10]] (cycle [0,1])
[1,4,5,8,9]

如果您知道您正在处理内部长度为 2 的列表,您可能应该改用成对的列表。

> zipWith ($) (cycle [fst, snd]) [(1,2),(3,4),(5,6),(7,8),(9,10)]
[1,4,5,8,9]

我非常喜欢@DanielWagner 的回答。第一个是如此简单和有效。他的第二个有点难理解,但也很简单。当理论很简单时,它会增加它们的准确性。这是我很抱歉的解决方案,但它确实使用了您的结构。 (关联列表是元组。建议您使用元组,但为此,您拥有的和可能需要的就可以了。)

a = [(0,[1,2]),(1,[3,4]),(2,[5,6]),(3,[7,8]),(4,[9,10])]

[if even i then x else y | (i,(x:y:z)) <- a]

[1,4,5,8,9]