首页 > 解决方案 > 如何通过列表中的索引从元组中选择元素?

问题描述

我想从列表中选择元素,[[1,2],[3,4],[5,6]] 第一个,第二个,第一个等等。我想我可以使用 zip 在对前面添加一个计数器并使用模数来选择零件,现在我的列表如下所示:

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

但是我现在如何选择元素?

伪代码将是

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

标签: listhaskelltuplesmodulo

解决方案


也许:

> 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]

推荐阅读